[Back]

// (c) Donn Felker 
// http://blog.donnfelker.com/post/HOWTO-Build-a-Store-Locator-in-ASPNET.aspx
// http://codeplex.com/StoreLocator 
//
// DotNetNuke® - http://www.dotnetnuke.com
// Copyright (c) 2002-2009
// by DotNetNuke Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
// to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions 
// of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
// DEALINGS IN THE SOFTWARE.
//

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DotNetNuke;
using DotNetNuke.Security;
using Microsoft.Win32;
using System.Globalization;
using System.Xml;
using System.Web.Configuration;
using System.Configuration;
using System.IO;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Services.Exceptions;
using DotNetNuke.Entities.Modules.Actions;
using DotNetNuke.UI.Utilities;
using System.Linq;
using System.Text;

namespace AdefWebserver.Modules.StoreLocator
{
    public partial class View : PortalModuleBase, IActionable
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if ((Page.IsPostBack == false))
                {
                    if (GetGoogleAPIKey() == "")
                    {
                        lblError.Text = "You must Set Google API Key in Module Settings";
                    }
                }

                Page.ClientScript.RegisterClientScriptInclude("GoogleMap", string.Format("http://maps.google.com/maps?file=api&v=2&key={0}", GetGoogleAPIKey()));
                lrlGoogleMap.Text = GetGoogleMapload();
                Page.ClientScript.RegisterStartupScript(this.GetType(), string.Format("GoogleMap{0}", Convert.ToString(ModuleId)), "GoogleMapload();", true);

            }
            catch (Exception ex)
            {
                Exceptions.ProcessModuleLoadException(this, ex);
            }
        }

        #region btnSubmit_Click
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            LoadMap();
        }
        #endregion

        #region IActionable Members
        public DotNetNuke.Entities.Modules.Actions.ModuleActionCollection ModuleActions
        {
            get
            {
                ModuleActionCollection Actions = new ModuleActionCollection();
                Actions.Add(GetNextActionID(), "Edit Locations", ModuleActionType.AddContent, "", "", EditUrl(), false, SecurityAccessLevel.Edit, true, false);
                return Actions;
            }
        }
        #endregion

        #region LoadMap
        private void LoadMap()
        {
            // Check for valid addrss
            if (txtAddress.Text.Trim() == "")
            {
                lblError.Text = "Must use a valid address.";
                lblError.Focus();
                pnlMap.Visible = false;
                return;
            }

            // Build address
            string strAddress = String.Format("{0}", txtAddress.Text.Trim());
            // Geocode Address
            GoogleGeoCoder.Coordinate Coordinate = GoogleGeoCoder.Geocode.GetCoordinates(strAddress, GetGoogleAPIKey());

            // Check for valid Geocode addrss
            if (Coordinate.Latitude == Convert.ToDecimal(0))
            {
                lblError.Text = "Must use a valid address.";
                lblError.Focus();
                return;
            }

            DisplayResults(Coordinate);
            pnlMap.Visible = true;
        }
        #endregion

        #region DisplayResults
        private void DisplayResults(GoogleGeoCoder.Coordinate coordinate)
        {
            List<ADefWebserver_Location> colADefWebserver_Location = GetLocationData(coordinate);

            // Set up the locations 
            searchResults.DataSource = colADefWebserver_Location;
            searchResults.DataBind();

            // Set result count
            totalResultCount.Text = colADefWebserver_Location.Count > 0 ? @"Total Matching Results <Br /> (up to 100 matches): " + colADefWebserver_Location.Count.ToString() : "No Results Found.";

            // Get the locations, in JSON format. 
            string jsonScript = GetJSONLocations(colADefWebserver_Location);

            // Get the home location (where the user entered their address) in JSON format. 
            string homeSpatialInfo = GetJsonHomeSpatialInfo(coordinate, txtAddress.Text);

            // Write the JSON objects to the client. 
            Page.ClientScript.RegisterClientScriptBlock(GetType(), "homeSpatialInfo", homeSpatialInfo, true);
            Page.ClientScript.RegisterClientScriptBlock(GetType(), "jsonMapObjects", jsonScript, true);
        }
        #endregion

        #region GetLocationData
        private List<ADefWebserver_Location> GetLocationData(GoogleGeoCoder.Coordinate coordinate)
        {
            StoreLocatorDALDataContext StoreLocatorDALDataContext = new StoreLocatorDALDataContext();
            return StoreLocatorDALDataContext.GetNearbyLocations(Convert.ToDouble(coordinate.Latitude), Convert.ToDouble(coordinate.Longitude), Convert.ToInt32(distanceDropDown.SelectedValue), 3961, ModuleId).ToList();
        }
        #endregion

        #region GetJSONLocations
        protected string GetJSONLocations(List<ADefWebserver_Location> data)
        {
            string firstLine = "var ProximityLocations = {\"locations\": [";
            string lastLine = "]};";

            string JSONObjectFormat = "\"name\": \"{0}\", \"address\": \"{1}\", \"urladdress\": \"{2}\", \"longitude\": \"{3}\", \"latitude\" : \"{4}\"";

            StringBuilder builder = new StringBuilder();
            builder.AppendLine(firstLine);

            string jsonLocation;
            string locationAddress;

            foreach (var row in data)
            {
                locationAddress = String.Format("{0}, {1}, {2}, {3}", row.Address, row.City, row.State, row.Zip);
                jsonLocation = String.Concat("{", String.Format(JSONObjectFormat,
                    HttpUtility.HtmlEncode(row.LocationName),
                    HttpUtility.HtmlEncode(locationAddress),
                    HttpUtility.UrlEncode(locationAddress),
                    row.Longitude,
                    row.Latitude),
                    "}", Environment.NewLine);
                builder.AppendLine(jsonLocation);

                // Only add comma if it is not the last row. The last row does not have a comma. 
                if (row.LocationId != data[data.Count - 1].LocationId)
                {
                    builder.Append(',');
                }
            }

            builder.AppendLine(lastLine);
            return builder.ToString();
        }
        #endregion

        #region GetJsonHomeSpatialInfo
        protected string GetJsonHomeSpatialInfo(GoogleGeoCoder.Coordinate coordinate, string fromAddress)
        {
            string top = "var homeSpatialInfo = {";
            string bottom = "};";
            string jsonVariable = String.Format("\"latitude\" : \"{0}\", \"longitude\" : \"{1}\", \"fromAddress\" : \"{2}\"", coordinate.Latitude, coordinate.Longitude, HttpUtility.UrlEncode(fromAddress));

            return String.Concat(top, jsonVariable, bottom, Environment.NewLine);
        }
        #endregion

        #region GetGoogleMapload
        private string GetGoogleMapload()
        {
            string strAppBase = Server.MapPath(this.TemplateSourceDirectory + @"\..\..\");

            string strFileNameAndPath =
                String.Format("{0}DesktopModules\\StoreLocator\\JavaScript\\GMapjs.txt", strAppBase);

            string strImagesPath = String.Format(@"http://{0}/{1}", Request.Url.Host, this.TemplateSourceDirectory);

            string strTextFile = GetTextFile(strFileNameAndPath);

            strTextFile = strTextFile.Replace("[MAPDIV]", this.map.ClientID);
            strTextFile = strTextFile.Replace("[MAPLOCATION]", strImagesPath);

            return strTextFile;
        }
        #endregion

        #region GetGoogleAPIKey
        string GetGoogleAPIKey()
        {
            string GoogleAPIKey = "";

            if ((Settings["GoogleAPIKey"]) != null)
            {
                GoogleAPIKey = Convert.ToString(Settings["GoogleAPIKey"]);
            }

            return GoogleAPIKey;
        }
        #endregion

        #region GetTextFile
        private String GetTextFile(string PathandScript)
        {
            string strTextFile;
            StreamReader reader = new StreamReader(PathandScript, System.Text.Encoding.Unicode);
            strTextFile = reader.ReadToEnd();
            reader.Close();
            reader = null;
            return strTextFile;
        }
        #endregion

        #region searchResults_ItemDataBound
        int _itemCount = 0;
        protected void searchResults_ItemDataBound(object sender, ListViewItemEventArgs e)
        {
            // Add the number to the screen for organization.
            if (e.Item.ItemType == ListViewItemType.DataItem)
            {
                _itemCount++;
                Literal locationNumber = (Literal)e.Item.FindControl("locationNumber");
                locationNumber.Text = _itemCount.ToString();
            }
        }
        #endregion
    }
}

Buy DotNetNuke Modules from Snowcovered

 DotNetNuke Powered!DotNetNuke is a registered trademark of DotNetNuke Corporation.