Plot Multiple Locations on Google Map Dynamically in ASP.Net

This article shows how to create an application that fetches multiple addresses from a database, calculates their longitude and latitude and then plots the location on the Google map dynamically.

Here, I use the "GoogleMaps.LocationServices" API to get the longitude and latitude of an address.

"GoogleMaps.LocatinServices" is a simple library that allows you to translate latitude/longitude to a region (state) and an address to a map point.

You can install it in your application by running the following command in the Package Manager Console:

PM> Install-Package GoogleMaps.LocationServices

Or you can download it from:
http://www.nuget.org/packages/GoogleMaps.LocationServices/

Let's now proceed to create the application.

First, suppose I have a database table that contains the multiple address. Each row in the table specifies a unique address, including Address, City, State, Zip and Country.

Now, I fetch this table in an ASP.NET application and load it into a DataTable object.

Note: Here, I skip the DataAccess layer to fetch the records from the database.

After getting all records from the database, then calculate the latitude / longitude of each address using the "GoogleLocationService" API.

For this purpose, I create a method that calculates the latitude / longitude of each address and stores them in a List Obect.

I have also defined a class to store various properties of an address to be displayed on the map.

Here is the class declaration.

  1. public class ProgramAddresses  
  2. {  
  3.     public ProgramAddresses()  
  4.     {        
  5.     }  
  6.     public string description { getset; }  
  7.     public double lng { getset; }  
  8.     public double lat { getset; }  
  9. }
Add the following namespaces to the .cs file:
  1. using System.Runtime.Serialization.Json;  
  2. using GoogleMaps.LocationServices;

In the following method, a list of all objects of the "ProgramAddresses" class are created and then this list is serialized to a JSON string using "JsonSerializer". After that, register this JsonString to the client-side using the "RegisterArrayDeclaration"() method.

  1. private void BindGMap(DataTable datatable)  
  2. {  
  3.   try  
  4.   {  
  5.     List<ProgramAddresses> AddressList = new List<ProgramAddresses>();  
  6.     foreach (DataRow dr in datatable.Rows)  
  7.     {  
  8.         string FullAddress = dr["Address"].ToString() + " " + dr["City"].ToString() + ", " + dr["Country"].ToString() + " " + dr["StateName"].ToString() + " " + dr["ZipCode"].ToString();  
  9.         ProgramAddresses MapAddress = new ProgramAddresses();  
  10.         MapAddress.description = FullAddress;  
  11.         var locationService = new GoogleLocationService();  
  12.         var point = locationService.GetLatLongFromAddress(FullAddress);  
  13.         MapAddress.lat = point.Latitude;  
  14.         MapAddress.lng = point.Longitude;  
  15.         AddressList.Add(MapAddress);  
  16.     }  
  17.    string jsonString = JsonSerializer<List<ProgramAddresses>>(AddressList);  
  18.    ScriptManager.RegisterArrayDeclaration(Page, "markers", jsonString);  
  19.    ScriptManager.RegisterStartupScript(Page, Page.GetType(), Guid.NewGuid().ToString(), "GoogleMap();"true);  
  20.    }  
  21.    catch (Exception ex)  
  22.    {   
  23.    }  
  24. } 

I have created a "GoogleMap()" method at the client-side to plot the location on the Google map.

Add the following script to the aspx page:

  1. <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyD4IuRFVcMjWo1qWvBrS3v4uvDXcCiq_c4&sensor=false">

The following is the Client-side GoogleMap() method functionality. In this JavaScript method, I used the jsonString to fetch the value that I registered in the pervious step. Going through the loop on the JsonString and plotting each location on the Google map.

  1. $(document).ready(function () {  
  2.   
  3. function GoogleMap() {  
  4.             var mapOptions = {  
  5.             center: new google.maps.LatLng(markers[0][0].lat, markers[0][0].lng),  
  6.             zoom: 2,  
  7.             mapTypeId: google.maps.MapTypeId.ROADMAP  
  8.         };  
  9.         var infoWindow = new google.maps.InfoWindow();  
  10.         var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);  
  11.         for (i = 0; i < markers[0].length; i++) {  
  12.             var data = markers[0][i];  
  13.             var marker = new google.maps.Marker({  
  14.                 position: new google.maps.LatLng(data.lat, data.lng),  
  15.                 map: map  
  16.             });   
  17.             (function (marker, data) {  
  18.                 google.maps.event.addListener(marker, "click"function (e) {  
  19.                     infoWindow.setContent(data.description);  
  20.                     infoWindow.open(map, marker);  
  21.                 });  
  22.             })(marker, data);  
  23.         }  
  24.     }   
  25. }
The aspx page code is as follows:
  1. <div id="map_canvas" style="border-top: none; width: 100%; margin-top: -1px; height: 250px; background-color: #FAFAFA; margin-top: 0px;">  
  2. </div>

The application displays the output like this:

plot-multiple-location-on-google-map.jpg


Similar Articles