Google Map 3 with Multiple locations in Asp.Net C#


Google Map Version 3 API is especially designed to be faster and more applicable to mobile devices, as well as traditional desktop browser applications ….read more from google map api document.

Click here to download the article

If you find the Google Map 3 code library useful, please consider donating

(No more API registration key needed for Version 3.0)

In this article I am going to explain how we can show multiple locations binding from code behind dynamically (database or any data source).  Couple of moths ago in Asp.Net forum I have posted an article using Google Map Version 2.0
(http://forums.asp.net/p/1507845/3584193.aspx#3584193). Version two was kind of messy Java Script code but now in Version 3.0 Google made it very simple.

Create a ASPX page and copy paste the following markup code..

<html>
<head runat=”server”>
<meta name=”viewport” content=”initial-scale=1.0, user-scalable=no” />
<meta http-equiv=”content-type” content=”text/html; charset=UTF-8″ />
<title>Google Map 3.0</title>
<style type=”text/css”>
.formatText{color:Green;font-size:11px;font-family:Arial;font-weight:bold;}
</style>
<script type=”text/javascript” src=”http://maps.google.com/maps/api/js?sensor=false“></script>
<script type=”text/javascript”>
var map;
function initialize() {
var myLatlng = new google.maps.LatLng(40.764015, -73.982797);
var myOptions = {
zoom: 8,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}

map = new google.maps.Map(document.getElementById(“map_canvas”), myOptions);

for (var i = 0; i < locationList.length; i++) {
var args = locationList[i].split(“,”);
var location = new google.maps.LatLng(args[0], args[1])
var marker = new google.maps.Marker({
position: location,
map: map
});
var j = i + 1;
marker.setTitle(message[i].replace(/(<([^>]+)>)/ig,””));
attachSecretMessage(marker, i);
}
}

function attachSecretMessage(marker, number) {
var infowindow = new google.maps.InfoWindow(
{ content: message[number],
size: new google.maps.Size(50, 50)
});
google.maps.event.addListener(marker, ‘click’, function() {
infowindow.open(map, marker);
});
}
</script>

</head>
<body style=”margin: 0px; padding: 0px;” onload=”initialize()”>
<form runat=”server”>
<div style=”padding-top: 10%;padding-left:20%”>
<div id=”map_canvas” style=”width: 50%; height: 50%”>
</div>
</div>
</form>
</body>
</html>

I have highlighted some of the lines from the above code

1)  The class formatText, simple css class for formating the info window text. You can replace your own css style here
.formatText{color:Green;font-size:11px;font-family:Arial;font-weight:bold;}

2) In the Java Script include statement I have mention sensor=false (because the sample app is targeting on web  page if you are using from Mobile application you should  set sensor=false. Read more about mobile app)

3) In the for loop I’ m using locationList.Length. Here locationList is Java Script array object which is getting generated from an Aspx code behind page and basically the locationList object has array of  Geo code information like Latitude and Longitude. In one my previous article I have explained how we can get the Geo-code location from an address using Yahoo API.

HTML out put

var locationList = new Array( ‘40.756012, -73.972614’ , ‘40.456012, -73.796087’ , ‘40.456012, -73.456807’ );

4) Splitting lattitude and longitude from the array object and assign it to Google function like below.

var args = locationList[i].split(“,”);

var location = new google.maps.LatLng(args[0], args[1])

5)   In marker we can able to set the title value and since I am using html tags and css class I’m replacing the html tags using the following syntax

marker.setTitle(message[i].replace(/(<([^>]+)>)/ig,””));

The rest of the mark up tags are same as mentioned in the Google doc.
So now we need to create the array from code behind. Copy paste the below code in to you code behind page load method
protected void Page_Load(object sender, EventArgs e)
 {
 List<String> oGeocodeList = new List<String>
 {
 " '40.756012, -73.972614' ",
 " '40.456012, -73.796087' ",
 " '40.456012, -73.456807' "
 };

 var geocodevalues = string.Join(",", oGeocodeList.ToArray());

 List<String> oMessageList = new List<String>
 {
 " '<span class=formatText >Google Map 3 Awesome !!!</span>' ",
 " '<span class=formatText>Made it very simple</span>' ",
 " '<span class=formatText>Google Rocks</span>' "
 };

 String message = string.Join(",", oMessageList.ToArray());

 ClientScript.RegisterArrayDeclaration("locationList", geocodevalues);

 ClientScript.RegisterArrayDeclaration("message", message);
 }

The above code List<String> oGeocodeList which creates a list of Geo-Code collection object. I have hard coded latitude and longitude (you can replace with your db procedure). Once you have created the list object we should convert in to Java Script array format like below

var geocodevalues = string.Join(“,”, oGeocodeList.ToArray()); and finally register the array

ClientScript.RegisterArrayDeclaration(“locationList”, geocodevalues); here locationList is the JS array object name.

Similarly I am creating the message array for the pop window (InfoWindow)

List oMessageList = new List
{
” ‘Google Map 3 Awesome !!!‘ “,
” ‘Made it very simple‘ “,
” ‘Google Rocks‘ ”
};

String message = string.Join(“,”, oMessageList.ToArray());   //convert list object to JS array format.

ClientScript.RegisterArrayDeclaration(“message“, message); //message = JS array object name.

Please refer the following links if you need to learn more about Map API 3.0

http://code.google.com/apis/maps/documentation/v3/introduction.html
http://code.google.com/apis/maps/documentation/v3/
http://code.google.com/apis/maps/documentation/v3/reference.html

Hope this help and If you have any comments, please feel free to write your feedback.

You can download the entire article from here or copy paste the URL

http://www.4shared.com/file/251039814/3e491cfc/GoogleMap3.html

If you find the Google Map 3 code library useful, please consider donating

Thanks
Deepu

Advertisements

76 thoughts on “Google Map 3 with Multiple locations in Asp.Net C#

  1. Thanks for nice code. I downloaded the code and tested well. Earlier I have created a sample html page and reading address detail from an xml file and display markers and its detail in infowindow dynamically, it is seems to be working correctly, but I noticed then whenever I enerate new xml file and the run the html page, it wont display the latest until I cleared the browser cache. Is there any way to manage this issue?

  2. Hi,

    This article was exactly what I was after, the ability to render points on a map from my own datasource. Unfortunately I can’t get it to work. I get a javascript error about the locationList being null in the initialze function despite loading and registering in the page load event. At the moment I am only using the code provided above but I have had to comment out the content type meta tag and remove the HTML doctype as well.

    Any thoughts?

    Thanks in advance,

    Mark

  3. Hi Deepu,

    I try your code but I have a problem with locationList.length. In the client side Javascript the array does not seem to have any value. What can I do wrong. I register the array in the server side as you did.

    Could you help?

    Thanks,

    hanifa

    1. You should replace the space and new line while creating array from C# code behind
      See the highlighted code

      ClientScript.RegisterArrayDeclaration(“locationList”, geocodevalues.Replace(“\r”,string.Empty).Replace(“\n”,string.Empty);

      ClientScript.RegisterArrayDeclaration(“message”, message).Replace(“\r”,string.Empty).Replace(“\n”,string.Empty);

      Hope this helps
      Thanks
      Deepu

  4. Hi Deepu,

    Below is my code following your help. No errors, but it didn’t show the map somehow. I tried it both in IE and Firefox. Firefox looked like it tried to download the map, but then couldn’t display. Would you please take a look at my code below and give me hint? Thanks so much. (Note: I also used my key for google, but you can test using yours or take it out).

    Tom

    ——————————————–

    Google Map 3.0

    var map;
    function initialize() {
    var myLatlng = new google.maps.LatLng(40.764015, -73.982797);
    var myOptions = {
    zoom: 8,
    center: myLatlng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
    }

    map = new google.maps.Map(document.getElementById(“map_canvas”), myOptions);

    for (var i = 0; i < locationList.length; i++) {
    var args = locationList[i].split(",");
    var location = new google.maps.LatLng(args[0], args[1])
    var marker = new google.maps.Marker({
    position: location,
    map: map
    });
    var j = i + 1;
    marker.setTitle(message[i].replace(/(]+)>)/ig,””));
    attachSecretMessage(marker, i);
    }
    }

    function attachSecretMessage(marker, number) {
    var infowindow = new google.maps.InfoWindow(
    { content: message[number],
    size: new google.maps.Size(50, 50)
    });
    google.maps.event.addListener(marker, ‘click’, function() {
    infowindow.open(map, marker);
    });
    }

    1. Hi Thomas,

      I have verified your code.. looks like..few pieces are missing … from your side,,

      1) You don’t need any google key for GMAP 3.0 version
      http://maps.google.com/maps/api/js?sensor=false
      2) Make sure you are initialize and declare the latitude and longitude array list along with TITLE
      var locationList = new Array(‘40.756012, -73.972614’, ‘40.456012, -73.796087’, ‘40.456012, -73.456807’);
      var message = new Array(‘My City 1’, ‘My City 2’, ‘My City 3’);

      3) Make sure you have to call the initialize() method in the body onload event
      <body style="margin: 0px; padding: 0px;" onload=”initialize();”>

      4) Also don’t forget to add the DIV object to render the map..
      div id=”map_canvas” style=”width:100%;height:90%;border:1px solid lightgrey;”

      I have sent a working copy of a html page

      Thanks
      Deepu

  5. Thanks Deepu. It’s working now. Quick question: how do you show the labels for the pins (e.g. A, B, C, etc) instead of the generic black dot on the pin?

    Thanks so much.

    Tom

  6. Hi Deepu,

    I have copied and ran ur code from this site; I could make it run and the locations values seems to load up ok in JS, however after page load nothing is loading up and its a blank page!!

    ASP.NET html page:

    Google Map 3.0

    .formatText{color:Green;font-size:11px;font-family:Arial;font-weight:bold;}

    var map;
    function initialize() {
    var myLatlng = new google.maps.LatLng(40.764015, -73.982797);
    var myOptions = {
    zoom: 8,
    center: myLatlng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
    }

    map = new google.maps.Map(document.getElementById(“map_canvas”), myOptions);
    debugger
    for (var i = 0; i < locationList.length; i++) {
    var args = locationList[i].split(",");
    var location = new google.maps.LatLng(args[0], args[1])
    var marker = new google.maps.Marker({
    position: location,
    map: map
    });
    var j = i + 1;
    marker.setTitle(message[i].replace(/(]+)>)/ig,””));
    attachSecretMessage(marker, i);
    }
    }

    function attachSecretMessage(marker, number) {
    var infowindow = new google.maps.InfoWindow(
    { content: message[number],
    size: new google.maps.Size(50, 50)
    });
    google.maps.event.addListener(marker, ‘click’, function() {
    infowindow.open(map, marker);
    });
    }

    CODE BEHIND:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;

    namespace MapApp
    {
    public partial class SimpleGMap : System.Web.UI.Page
    {
    protected void Page_Load(object sender, EventArgs e)
    {

    List oGeocodeList = new List

    { ” ‘40.756012, -73.972614’ “,
    ” ‘40.456012, -73.796087’ “,
    ” ‘40.456012, -73.456807’ ”
    };

    var geocodevalues = string.Join(“,”, oGeocodeList.ToArray());

    List oMessageList = new List
    { ” ‘Google Map 3 Awesome !!!’ “,
    ” ‘Made it very simple’ “,
    ” ‘Google Rocks’ ”
    };

    String message = string.Join(“,”, oMessageList.ToArray());
    ClientScript.RegisterArrayDeclaration(“locationList”, geocodevalues.Replace(“\r”,string.Empty).Replace(“\n”,string.Empty));
    //ClientScript.RegisterArrayDeclaration(“message”, message);

    // ClientScript.RegisterArrayDeclaration(“locationList”, geocodevalues.Replace(“\r”,string.Empty).Replace(“\n”,string.Empty);

    ClientScript.RegisterArrayDeclaration(“message”, message.Replace(“\r”,string.Empty).Replace(“\n”,string.Empty));
    }
    }
    }

    Am i doing something wrong? Need urgent Help!

    1. Hi Dipanjan,

      I have sent a attached file (full html version of google map 3.0). From your above code I can see javascript and code behind..

      make sure mark up tag also there with body onload function initialize();codeAddress()”

      <input name="txtAddressFormated" type="text" id="txtAddressFormated" style="display:none;" value="Heading goes here” />

      Hope this helps
      Thanks
      Deepu

  7. Thanks Deepu,

    Excellent help doc, Also i could make this code of urs to work, after some trouble shooting observed that i need to mension height and width to form tag for it to work. Couple of question:
    1. What if i need to load batches of diffent color markers, can they be added simultaniously, how would i put that in script.
    2. Observed that the on click doesnt die if i click another marker, what if i want to show one click at a time.

    your giudance would be highly appreciated!

    Thanks,
    Dipanjan

  8. Thanks Deepu, your code was excellent. You have passed latitude and longitudes directly, my doubt is can this be done by passing address? Can you provide a code sample illustrating how to place multiple markers on Google map for different addresses? I have seen some examples using gecoder.geocode() function to convert address to latitude, longitude but I can’t get this to work! Please provide a working example for this scenario…

  9. Thanks Deepu, your code was excellent. You have passed latitude and longitude directly, my doubt is can this be done by passing address? Can you provide a code sample illustrating how to place multiple markers on Google map for different addresses? I have seen some examples using gecoder.gecode function but I can’t get this to work!

  10. You have passed latitude and longitude directly, my doubt is can this be done by passing address? Can you provide a code sample illustrating how to place multiple markers on Google map for different addresses? I have seen some examples using gecoder.gecode function but I can’t get this to work! Please keep up your good work, codes in your blogs are very useful!

    1. Hi Banu,

      I have updated the code below finding geocode service from a address

      var geocoder;
      var map;
      var infoWindow;

      function initialize() {
      geocoder = new google.maps.Geocoder();
      var latlng = new google.maps.LatLng(37.09024, -95.712891);
      var myOptions = {
      zoom: 14,
      center: latlng,
      mapTypeId: google.maps.MapTypeId.ROADMAP
      }
      map = new google.maps.Map(document.getElementById(“map_canvas”), myOptions);
      infowindow = new google.maps.InfoWindow();
      }

      function codeAddress() {
      var address = document.getElementById(“txtAddress”).value;
      if (geocoder && address != “”) {
      geocoder.geocode({ ‘address’: address }, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
      map.setCenter(results[0].geometry.location);
      var marker = new google.maps.Marker({
      map: map,
      position: results[0].geometry.location
      });
      addMarkers(results[0].geometry.location);
      } else {
      document.getElementById(“map_canvas”).style.display = “none”;
      }
      });
      }
      else {
      document.getElementById(“map_canvas”).style.display = “none”;
      document.getElementById(“divMsg”).innerHTML = “Google map is not available for this address”;
      }
      }
      function addMarkers(geoCode) {
      geoCode = String(geoCode).replace(“)”, “”).replace(“(“, “”);
      var arr = geoCode.split(“,”);
      var formattedAddress = document.getElementById(“txtAddressFormated”).value;
      infowindow.setContent(formattedAddress);
      infowindow.setPosition(new google.maps.LatLng(arr[0], arr[1]));
      infowindow.open(map);
      }

      <input name="txtAddressFormated" type="text" id="txtAddressFormated" style="display:none;" value="Heading goes here” />

      Hope this helps
      Thanks
      Deepu

  11. Hi Deepu, Thanks for your demo, works great. Is it however possible to add a text and link to the demo in the popup? Would help people a lot. THanks Nick

    1. You are welcome Nick, It is pretty easy to add a link and text. See the following code

      List oMessageList = new List
      {
      ” ‘<span class=”formatText”>Google Map 3 Awesome !!!</span><br /><a>Take me to google</a>’ “,
      ” ‘<span class=”formatText”>Made it very simple</span>’ “,
      ” ‘<span class=”formatText”>Google Rocks</span>’ ”
      };

      Hope this helps

      Thanks
      Deepu

  12. This idea of a Google maps is incredible. Google, indeed, is always leading in providing such services. This will improve their online services by providing specific local business locations, on the other hand, they are giving away the opportunity to every businesses in the local areas to be exposed or be advertised.
    I’m just wondering if it can be made available on mobile gadgets or particularly in our own cars. Good idea. Isn’t it?

  13. Hi

    Can anyone tell me when i use in the page. this code is not working. When I remove that that code is working fine..

    Any Suggestions?

      1. Its not an error. When i used default DOCTYPE itz not displaying the Marker positions, When i used !DOCTYPE html “-//W3C//DTD XHTML 1.0 Strict//EN”
        “http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd”, Its working fine.

  14. Hi Deepu
    Thanks for this article, it is exactly what I want to do.
    Unfortunately my code brings up an empty page. I looked at the source and the GPS points I load from code behind are in the script.
    I have worked through all the other comments, but still nothing.
    Please help !!!
    Regards
    Hein
    Below is my Code:

    <%—-%>

    Google Map 3.0

    <%–<script src="http://maps.google.com/maps?file=api&v=2&key=&sensor=false
    type=”text/javascript”>–%>

    .formatText{color:Green;font-size:11px;font-family:Arial;font-weight:bold;}

    var map;
    function initialize() {
    var myLatlng = new google.maps.LatLng(40.764015, -73.982797);
    var myOptions = {
    zoom: 8,
    center: myLatlng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
    }

    map = new google.maps.Map(document.getElementById(“map_canvas”), myOptions);

    for (var i = 0; i < locationList.length; i++) {
    var args = locationList[i].split(",");
    var location = new google.maps.LatLng(args[0], args[1])
    var marker = new google.maps.Marker({
    position: location,
    map: map
    });
    var j = i + 1;
    marker.setTitle(message[i].replace(/(]+)>)/ig,””));
    attachSecretMessage(marker, i);
    }
    }

    function attachSecretMessage(marker, number) {
    var infowindow = new google.maps.InfoWindow(
    { content: message[number],
    size: new google.maps.Size(50, 50)
    });
    google.maps.event.addListener(marker, ‘click’, function() {
    infowindow.open(map, marker);
    });
    }

    /// Code behind ///

    protected void Page_Load(object sender, EventArgs e)
    {

    List oGeocodeList = new List
    {
    ” ‘40.756012, -73.972614’ “,
    ” ‘40.456012, -73.796087’ “,
    ” ‘40.456012, -73.456807’ ”
    };
    var geocodevalues = string.Join(“,”, oGeocodeList.ToArray());

    List oMessageList = new List
    {
    ” ‘Google Map 3 Awesome !!!’ “,
    ” ‘Made it very simple’ “,
    ” ‘Google Rocks’ ”
    };
    String message = string.Join(“,”, oMessageList.ToArray());

    //ClientScript.RegisterArrayDeclaration(“locationList”, geocodevalues);
    //ClientScript.RegisterArrayDeclaration(“message”, message);
    ClientScript.RegisterArrayDeclaration(“locationList”, geocodevalues.Replace(“\r”,string.Empty).Replace(“\n”,string.Empty));
    ClientScript.RegisterArrayDeclaration(“message”, message.Replace(“\r”,string.Empty).Replace(“\n”,string.Empty));
    }
    }

  15. Hi deepu,

    could you give an example of replacing the hard coded geocodes with the db procedure?? Im using a MySQL database but and db procedure would give insight.

    Thanks 🙂

    1. Here you go..

      List < string > oGeocodeList = new List < string > ();

      List < string > oMessageList = new List < string > ();

      //add your mysql connection logic

      while (myDataReader.Read())
      {

      //assume that you have a columns in mysql db called Latitude, Longitude & Description

      //appending latitude & longitude
      string tempGeoCode = myDataReader.GetString(“Latitude”).ToString() + “, ” + myDataReader.GetString(“Longitude”).ToString();

      oGeocodeList.Add(tempGeoCode);

      //adding description to string array
      oMessageList.Add(myDataReader.GetString(“Description”).ToString());

      }

      var geocodevalues = string.Join(“,”, oGeocodeList.ToArray());

      String message = string.Join(“,”, oMessageList.ToArray());

      ClientScript.RegisterArrayDeclaration(“locationList”, geocodevalues);

      ClientScript.RegisterArrayDeclaration(“message”, message);

      Also refer the following links

      http://www.java2s.com/Tutorial/ASP.NET/0360__ADO.net-Database/ReadscalardatafromMySQLdatabasebyusingOdbcCommand.htm
      http://forums.asp.net/p/1205327/2108538.aspx
      http://www.codeproject.com/KB/database/ConnectMySQL.aspx

      Note : I have not compiled this code..

      Hope this helps
      Thanks
      Deepu

  16. Hi Deepu,

    Great tutorials! I’ve tried both of your multi-markers and geocode service code, and yet to try the DB one. Performance wise, do you agree that using the lat/long will run faster than using an actual address?

    I have about 400 markers to drop in onto the map.
    1) Currently, I only have the actual address, not lat/long yet. Is there a way to return the actual lat/long in numerical format? The geocode service puts a marker on the address and only shows the address in the ballon. I’d like to try having the code loops through all the records and update its lat/long info.

    2) With so many markers and potentially having some hovering over the same area. Is there an easy way to do clustering based on your code?

    3) Does Google Maps Api offer a way to calcuate driving distance between 2 points?

    Thank you, any pointers is appreciated!

    Blue

    1. Hi SmurfBlue,

      YES, lat/long will run faster than using an actual address. I have written a method for getting lat / long from yahoo geo coding service

      If you want you can try it out

      ======

      GetGeoCodeInformation(“3050 University Ave, West Des Moines, IA 50266”);

      public static string GetGeoCodeInformation(string address)
      {
      string retValue = string.Empty;
      try
      {
      //address = “3050 University Ave, West Des Moines, IA 50266”;

      string YAHOO_APP_ID = “REPLACE WITH YOUR APP ID”;
      string YAHOO_API_URL = “http://local.yahooapis.com/MapsService/V1/geocode?appid=” + YAHOO_APP_ID + “&” + address;

      WebRequest _request = WebRequest.Create(YAHOO_API_URL);

      WebResponse _response = _request.GetResponse();

      StreamReader reader = new StreamReader(_response.GetResponseStream());

      string sGeoResponse = reader.ReadToEnd();

      XmlDocument xmlDoc = new XmlDocument();

      if ((sGeoResponse.Length > 0))
      {
      xmlDoc.LoadXml(sGeoResponse);

      if ((xmlDoc.GetElementsByTagName(“Result”) != null))
      {
      if (!string.IsNullOrEmpty(xmlDoc.GetElementsByTagName(“Latitude”)[0].InnerText.ToString()))
      {
      retValue += xmlDoc.GetElementsByTagName(“Latitude”)[0].InnerText.ToString() + “,”;
      }

      if (!string.IsNullOrEmpty(xmlDoc.GetElementsByTagName(“Longitude”)[0].InnerText.ToString()))
      {
      retValue += xmlDoc.GetElementsByTagName(“Longitude”)[0].InnerText.ToString();
      }
      }
      }
      _request = null;
      _response = null;
      reader = null;
      xmlDoc = null;
      }
      catch (Exception exp)
      {
      retValue = “NOT_DEFINED”;
      }
      return retValue;
      }

      ========

      Also google offers a rich set of api’s for calculating driving distance between points

      Please refer the following links if you need to learn more about Map API 3.0

      http://code.google.com/apis/maps/documentation/v3/introduction.html
      http://code.google.com/apis/maps/documentation/v3/
      http://code.google.com/apis/maps/documentation/v3/reference.html

      Hope this helps
      Thanks
      Deepu

  17. Hi Deepu,

    Great work! This tutorial is nice simple and clean.

    I’m having trouble with the secret message javascript function. I get a null error on map when clicking on a marker. Have you seen this error before?

    -Nick

  18. Hey thanks for the guide here. However, after i converted the code under page load to vb.net. it looks like i have some problem. do you have a vb.net code for the page load?

  19. Hi
    ,
    Great work! This tutorial is nice simple and clean.
    I’m having trouble with the secret message javascript function. I get a null error on map when clicking on a marker. Have you seen this error before?

  20. Thanks
    Deepumi !!!

    ‘For vb.net page load

    Dim oGeocodeList As List(Of String) = New List(Of String)
    oGeocodeList.Add(” ‘40.756012, -73.972614’ “)
    oGeocodeList.Add(” ‘40.456012, -73.796087’ “)
    oGeocodeList.Add(” ‘40.456012, -73.456807’ “)

    Dim geocodevalues As String = String.Join(“,”, oGeocodeList.ToArray())

    Dim oMessageList As List(Of String) = New List(Of String)
    oMessageList.Add(” ‘Google Map 3 Awesome !!!’ “)
    oMessageList.Add(” ‘Made it very simple’ “)
    oMessageList.Add(” ‘Google Rocks’ “)

    Dim message As String = String.Join(“,”, oMessageList.ToArray())

    ClientScript.RegisterArrayDeclaration(“locationList”, geocodevalues)

    ClientScript.RegisterArrayDeclaration(“message”, message)

  21. Above code is not working….
    Gives me jscript error locationList is undefined

    below is my HTML Code

    Google Map 3.0

    .formatText{color:Green;font-size:11px;font-family:Arial;font-weight:bold;}

    var map;
    function initialize()
    {
    var myLatlng = new google.maps.LatLng(18.56, 72.51);
    var myOptions =
    {
    zoom: 8,
    center: myLatlng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
    }

    map = new google.maps.Map(document.getElementById(“map_canvas”), myOptions);

    for (var i = 0; i < locationList.length; i++)
    {
    var args = locationList[i].split(",");
    var location = new google.maps.LatLng(args[0], args[1]);
    var marker = new google.maps.Marker
    (
    {
    position: location,
    map: map
    }
    );
    var j = i + 1;
    marker.setTitle(message[i].replace(/(]+)>)/ig, “”));
    attachSecretMessage(marker, i);
    }
    }

    function attachSecretMessage(marker, number)
    {
    var infowindow = new google.maps.InfoWindow
    (
    {
    content: message[number],
    size: new google.maps.Size(50, 50)
    }
    );
    google.maps.event.addListener
    (
    marker, ‘click’, function()
    {
    infowindow.open(map, marker);
    }
    );
    }

    Code behind

    protected void Page_Load(object sender, EventArgs e)
    {
    List oGeocodeList = new List();
    List oMessageList = new List();

    string connectionString = “Initial Catalog=HCLTransactDB;data source=DEV-ML\\SQL2008;Integrated Security=SSPI;”;
    SqlConnection conn = new SqlConnection(connectionString);
    conn.Open();
    SqlCommand cmd = null;

    try
    {
    cmd = conn.CreateCommand();
    cmd.CommandText = “Select * from LocationsDetailsTbl”;
    cmd.CommandText += “;”;
    SqlDataReader prd = cmd.ExecuteReader();
    if (prd.HasRows)
    {
    while (prd.Read())
    {
    string tempGeoCode = prd.GetString(0).ToString() + “,” + prd.GetString(1).ToString();
    oGeocodeList.Add(tempGeoCode);
    string Address = prd.GetString(2).ToString();
    oMessageList.Add(Address);
    }
    }
    }
    catch (Exception ex)
    {
    string Error = ex.Message;
    }
    finally
    {
    conn.Close();
    cmd = null;
    }

    string geocodevalues = string.Join(“,”, oGeocodeList.ToArray());

    string message = string.Join(“,”, oMessageList.ToArray());

    ClientScriptManager cs = this.Page.ClientScript;

    cs.RegisterArrayDeclaration(“locationList”, geocodevalues);

    cs.RegisterArrayDeclaration(“message”, message);
    }

    1. problem solved
      just needed few single quotes when populating the list

      code is below, only the changed code

      string tempGeoCode = “‘” + prd.GetString(0).ToString() + “,” + prd.GetString(1).ToString() + “‘”;
      oGeocodeList.Add(tempGeoCode);
      string Address = “‘” + prd.GetString(2).ToString() + “‘”;
      oMessageList.Add(Address);

  22. Thanks for this post. It helps a lot. Although I am running into issues with my setup. Here is what I have. I have a real estate Access database. The database has property information including lat/long. I am pulling the lat/log and other pertaining information about a property (like address and such). I like to use the map to display all of them on a map. The filters are user driven. So if they select only a zip code it pulls smaller list as sompare to everything if they don’t specify anything. So the list can rather get really large.

    I would appreciate your advise in this regard. And any sample code will also be helpfull.

    thanks
    Kalim

  23. Hi, So far I have been unable to run the code in suggested in this page. I get a blank page. Please email me full html version of google map 3.0 if possible.

    thanks a lot
    Kalim

  24. below is my server side code i didn’t change anything in javascript and receiving error locationList is undefined please help me out

    protected void Page_Load(object sender, EventArgs e)
    {
    SqlConnection sqlCon = new SqlConnection();
    sqlCon.ConnectionString = “server=ROD-DBSERVER\\SQL2008;database=ROD42_ENT_QA_TC18;user id=sa;password=macrosoft”;
    sqlCon.Open();
    SqlDataAdapter sqlAdp = new SqlDataAdapter(“SELECT * FROM LA_LODGING_AREA”, sqlCon);
    DataSet ds = new DataSet();
    sqlAdp.Fill(ds);
    List oGeocodeList = new List();

    foreach (DataRow dr in ds.Tables[0].Rows)
    {
    oGeocodeList.Add(“‘” + dr[“LA_ADDRESS”].ToString() + “,” + dr[“LA_CITY”].ToString() + “,” + dr[“ST_STATE”].ToString() + “,” + dr[“LA_ZIP”].ToString() + “‘”);
    //oGeocodeList.Add(str);
    }

    var geocodevalues = string.Join(“,”, oGeocodeList.ToArray());

    ClientScript.RegisterArrayDeclaration(“locationList”, geocodevalues.Replace(“\r”,string.Empty).Replace(“\n”,string.Empty));

    }

    1. You must only assign latitude and longitude in the oGeocodeList array object..

      List oGeocodeList = new List
      {
      ” ‘40.756012, -73.972614’ “,
      ” ‘40.456012, -73.796087’ “,
      ” ‘40.456012, -73.456807’ ”
      };

      In your case..

      List oGeocodeList = new List
      List oMessageList = new List

      foreach (DataRow dr in ds.Tables[0].Rows)
      {
      oGeocodeList.Add(“‘” + dr[“LA_ADDRESS”].ToString() + “‘”); //should be latitude and longitude like this format (40.756012, -73.972614).
      oMessageList .Add(“‘” + dr[“LA_CITY”].ToString() + “,” + dr[“ST_STATE”].ToString() + “,” + dr[“LA_ZIP”].ToString() + “‘”);

      }

      Hope this helps
      Thanks
      Deepu

      1. function ViewMap() {
        if (spread.GetRowCount() > 0) {
        var locations = new Array();
        for (i = 0; i < spread.GetRowCount(); i++) {
        locations.push("'" + spread.GetValue(i, 2) + ', ' + spread.GetValue(i, 3) + ', ' + spread.GetValue(i, 4) + ((trim(spread.GetValue(i, 5)) != '') ? ', ' + spread.GetValue(i, 5) : '') + ', USA' + "'");
        }
        var args = new Array();
        args[0] = window;
        window.showModalDialog("../Maps/Gmap3.aspx?BackPage=MANAGEVENDOR&locationArray=" + locations, args, "dialogHeight:670px;dialogWidth:850px;scroll:yes;toolbar:no;status:no;help:no;");
        }
        return false;
        }

        I am doing this for values and the problems is that it is not showing more then 11 pins thanks in advance

  25. Hi, Thanks for sharing. This an awesome post. Keep your good work. Meanwhile, do you know how can convert the grid reference (eg.TQ23015240) to lat/lng (51.257503 / -0.23856134) in the asp.net code behind?

  26. Hi, couple of people here have had the same issue as me…no errors, but just a blank page, some people have said they found the issue, but I can’t seem to….can you help, or send me a working page, really need to use this as an example today if possible.

    Thanks for any help in advance 🙂

  27. Hi Deepu,
    I tried with ur code.but its displaying blank page.please help me.Below is my code

    Google Map 3.0

    var map;
    function initialize() {
    var myLatlng = new google.maps.LatLng(40.764015, -73.982797);
    var myOptions = {zoom: 8, center: myLatlng, mapTypeId: google.maps.MapTypeId.ROADMAP }
    map = new google.maps.Map(document.getElementById(“map_canvas”), myOptions);
    for (var i = 0; i < locationList.length; i++) {
    var args = locationList[i].split(",");
    var location = new google.maps.LatLng(args[0], args[1])
    var marker = new google.maps.Marker({position: location,map: map});
    var j = i + 1;
    marker.setTitle(message[i].replace(/(]+)>)/ig, “”));
    attachSecretMessage(marker, i);
    }
    }

    function attachSecretMessage(marker, number) {
    var infowindow = new google.maps.InfoWindow({ content: message[number],size: new google.maps.Size(50, 50)});
    google.maps.event.addListener(marker, ‘click’, function() {infowindow.open(map, marker);});
    }

    Code Behind

    List oGeocodeList = new List {” ‘17.3761525, 78.5462098’ “,” ‘17.374445, 78.505896’ “,” ‘17.3404791, 78.3088258’ “};
    var geocodevalues = string.Join(“,”, oGeocodeList.ToArray());

    List oMessageList = new List
    {” ‘Google Map 3 Awesome !!!’ “,” ‘Made it very simple’ “,” ‘Google Rocks’ “};
    String message = string.Join(“,”, oMessageList.ToArray());
    ClientScript.RegisterArrayDeclaration(“locationList”, geocodevalues);
    ClientScript.RegisterArrayDeclaration(“message”, message);

  28. can u please send me the Full code Aspx&code behind for
    method for getting lat / long from yahoo geo coding service

    My requirement is If i give Location name as list,google marker able to mark that Locations On Google map

    thanks in Advance

  29. Hi There,

    I used this code but I could not get it to work as is. I had to comment the <doctype in the aspx page. Then it worked like magic. I thought this might be helpful to someone who faces the blank page issue.

    Thanks,
    tee

  30. i try your code but i got a blank page and some tome got a error “Microsoft JScript runtime error: Object expected” in Body Part. if u pls help me and give me replay as soon as possible pls. the following is the code :

    Google Map 3.0

    .formatText{color:Green;font-size:11px;font-family:Arial;font-weight:bold;}

    var map;
    function initialize() {
    var myLatlng = new google.maps.LatLng(40.764015, -73.982797);
    var myOptions = {
    zoom: 8,
    center: myLatlng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
    }

    map = new google.maps.Map(document.getElementById(“map_canvas”), myOptions);

    for (var i = 0; i < locationList.length; i++) {
    var args = locationList[i].split(",");
    var location = new google.maps.LatLng(args[0], args[1])
    var marker = new google.maps.Marker({
    position: location,
    map: map
    });
    var j = i + 1;
    marker.setTitle(message[i].replace(/(]+)>)/ig,””));
    attachSecretMessage(marker, i);
    }
    }

    function attachSecretMessage(marker, number) {
    var infowindow = new google.maps.InfoWindow(
    { content: message[number],
    size: new google.maps.Size(50, 50)
    });
    google.maps.event.addListener(marker, ‘click’, function() {
    infowindow.open(map, marker);
    });
    }

  31. Excellent code Deepu.

    I have applied your code to a vb.net web application Iam working on. The big problem I have is that none of the markers are being added. here is my code. I would be very grateful if you could point me in the right direction…

    javascript

    var map; // Creates the map
    var store1 = new google.maps.LatLng(55.008851, -1.609765);/ /opening point
    function initialize() {
    //xloc = $.url().param(‘x’);
    //yloc = $.url().param(‘y’);
    //alert(“Easting is: ” + xloc + ” Northing is : ” + yloc);
    //Lat = PageMethods.LatLonConversions.ConvertOSToLatLon(xloc, yloc).Latitude.ToString()
    //Lon = PageMethods.LatLonConversions.ConvertOSToLatLon(xloc, yloc).Longitude.ToString()
    //55.008748 -1.611330
    map = new google.maps.Map(document.getElementById(‘map’), {
    zoom: 18,
    center: new google.maps.LatLng(55.008851, – 1.609765),
    mapTypeId: google.maps.MapTypeId.ROADMAP
    });
    // add a starting marker to the map
    var marker1 = new google.maps.Marker({
    position: store1,
    map: map,
    title: “You are Here”
    });
    for (var i = 0; i )/ig, “”)); //this line shows an error
    attachSecretMessage(marker, i);

    }
    }

    function attachSecretMessage(marker, number) {
    var infowindow = new google.maps.InfoWindow(
    { content: message[number],
    size: new google.maps.Size(50, 50)
    });
    google.maps.event.addListener(marker, ‘click’, function() {
    infowindow.open(map, marker);
    });
    }

    code behind

    Dim oGeocodeList As New List(Of String)()
    Dim oMessageList As New List(Of String)()
    Dim Amessage As String = Nothing
    While dr.Read()
    Eastb = dr.Item(“easting”) ‘(“easting”).ToString
    Northb = dr.Item(“northing”) ‘(“northing”).ToString
    NearLat = LatLonConversions.ConvertOSToLatLon(CDbl(Eastb), CDbl(Northb)).Latitude.ToString()
    NearLon = LatLonConversions.ConvertOSToLatLon(CDbl(Eastb), CDbl(Northb)).Longitude.ToString()
    Dim tempGeoCode As String = “‘” + NearLat.ToString() + “,” + NearLon.ToString() + “‘”
    oGeocodeList.Add(tempGeoCode)
    ‘Dim tempGeoCode As String = dr.GetString(“DESCRIPTION”).ToString() + “, ” + NearLat.ToString + “, ” + NearLon.ToString
    oMessageList.Add(“‘” + dr.GetString(“DESCRIPTION”).ToString() + “‘”)
    End While
    Dim geocodevalues As String = String.Join(“,”, oGeocodeList.ToArray())
    Amessage = String.Join(“,”, oMessageList.ToArray())

    ClientScript.RegisterArrayDeclaration(“locationList”, geocodevalues)
    ClientScript.RegisterArrayDeclaration(“message”, Amessage)
    Rob

  32. Hi Sir,
    I am not able to visible the map. It is showing empty page. i used exactly same code what u had given above. i am searching for this type of code since 4 days. help me sir.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s