Click here to Skip to main content
15,885,366 members
Articles / Web Development / ASP.NET
Tip/Trick

Google Map with JSON

Rate me:
Please Sign up or sign in to vote.
4.87/5 (16 votes)
11 Mar 2015BSD2 min read 56.7K   2.5K   27   10
Google Map with JSON

Sample Image - maximum width is 600 pixels

Introduction

Most of us are familiar with Google map. Google has provided very rich APIs to use in our own application. I was using an ASP.NET Google Maps User Control name GoogleMaps.Subgurim.NET for my marker and polygon drawing for a long time. It is an excellent tool indeed. Please check the below mentioned link for more details:

I needed some more functionality which could be easily done by Google Map API. But when I was searching for an example, most of the examples were based on JavaScript but I needed server side functionality because my latitude & longitude and description data would come from database and definitely I needed some searching functionality. In this tip, I would like to show you how you can achieve this functionality with json.

Please check the below mentioned link for more details about json:

Background

I assume you have a basic knowledge of ASP.NET and C#.NET, and so on.

Using the Code

Within the head section of an HTML document, include this script reference to the Google Maps API; the key should be changed if you need to upload this HTML into a web server.

JavaScript
	<script type='text/javascript'
src='http://maps.googleapis.com/maps/api/js?sensor=false'></script>

Then add:

JavaScript
<script type="text/javascript"
src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>

Now add the main JavaScript function to get data from server side and draw map with marker:

JavaScript
var map;

function CreateMarker() {
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "Default.aspx/BindMapMarker",
        data: "{}",
        dataType: "json",
        success: function (data) {
            var myOptions = {
                center: new google.maps.LatLng(data.d[0].Latitude, data.d[0].Longitude),
                zoom: 14,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            };
            map = new google.maps.Map(document.getElementById("idgoogleMap"), myOptions);

            var ltlng = [];

            for (var i = 0; i <= data.d.length; i++) {

                ltlng.push(new google.maps.LatLng(data.d[i].Latitude, data.d[i].Longitude));

                marker = new google.maps.Marker({
                    map: map,
                    animation: google.maps.Animation.DROP,
                    icon: '3.png',
                    title: data.d[i].LocationName,
                    position: ltlng[i]
                });


                (function (marker, i) {

                    google.maps.event.addListener(marker, 'click', function () {

                        infowindow = new google.maps.InfoWindow({ maxWidth: 250 });
                        infowindow.setContent(data.d[i].LocationName);
                        infowindow.open(map, marker);

                    });

                })(marker, i);
            }
        },
        error: function (result) {
            alert("Error");
        }
    });
};

//google.maps.event.addDomListener(window, 'load', CreateMarker());

Now add server side code.

C#
[WebMethod]
  public static MAPS[] BindMapMarker()
  {
      DataSet ds = new DataSet();
      DataTable dt = new DataTable();
      List<maps> lstMarkers = new List<maps>();
      try
      {

          dt.Columns.Add("LocationName");
          dt.Columns.Add("Latitude");
          dt.Columns.Add("Longitude");

          dt.Rows.Add("LocationName 1", "23.722449", "90.401508");
          dt.Rows.Add("LocationName 2", "23.715667", "90.384295");
          dt.Rows.Add("LocationName 3", "23.723928", "90.405924");
          dt.Rows.Add("LocationName 4", "23.716426", "90.395794");
          dt.Rows.Add("LocationName 5", "23.721985", "90.399379");

          foreach (DataRow dtrow in dt.Rows)
          {
              MAPS objMAPS = new MAPS();
              objMAPS.LocationName = dtrow[0].ToString();
              objMAPS.Latitude = dtrow[1].ToString();
              objMAPS.Longitude = dtrow[2].ToString();
              lstMarkers.Add(objMAPS);
          }
      }
      catch (Exception ex)
      {
          throw ex;
      }

      return lstMarkers.ToArray();
  }

  public class MAPS
  {
      public string LocationName;
      public string Latitude;
      public string Longitude;
  }

Analysis of Client Side Code

jQuery allows you to call Server Side ASP.NET methods from client side without any PostBack. Actually it is an AJAX call to the server but it allows to call the method or function from server side.

Image 2

Then I have added some option in map object. Here data is an object return from server side function BindMapMarker().

Image 3

Now Load Data in marker object.

Image 4

Add Click event functionality in marker object.

Image 5

Analysis of Server Side Code

This code calls JavaScript function CreateMarker() when page is loading.

C#
if (!ClientScript.IsStartupScriptRegistered("window"))
{
    Page.ClientScript.RegisterStartupScript(this.GetType(), "window", "CreateMarker();", true);
}

An important thing to note is that the method is declared as static (C#) and also it is declared as Web Method unless you do this you won’t be able to call the methods. Rest of the code is self explanatory. For the sake of simplicity, I have used dataset with fixed value. Just populate the dataset with your SQL value and you are ready to go.

C#
[WebMethod]
  public static MAPS[] BindMapMarker()
  {
      DataSet ds = new DataSet();
      DataTable dt = new DataTable();
      List<maps> lstMarkers = new List<maps>();
      try
      {
          dt.Columns.Add("LocationName");
          dt.Columns.Add("Latitude");
          dt.Columns.Add("Longitude");

          dt.Rows.Add("LocationName 1", "23.722449", "90.401508");
          dt.Rows.Add("LocationName 2", "23.715667", "90.384295");
          dt.Rows.Add("LocationName 3", "23.723928", "90.405924");
          dt.Rows.Add("LocationName 4", "23.716426", "90.395794");
          dt.Rows.Add("LocationName 5", "23.721985", "90.399379");

          foreach (DataRow dtrow in dt.Rows)
          {
              MAPS objMAPS = new MAPS();
              objMAPS.LocationName = dtrow[0].ToString();
              objMAPS.Latitude = dtrow[1].ToString();
              objMAPS.Longitude = dtrow[2].ToString();
              lstMarkers.Add(objMAPS);
          }
      }
      catch (Exception ex)
      {
          throw ex;
      }

      return lstMarkers.ToArray();
  }

  public class MAPS
  {
      public string LocationName;
      public string Latitude;
      public string Longitude;
  }

References

Credit

I would like to give credit to my colleague khandaker Waliur Rahman <waliur.rahman@icddrb.org> for his contribution.

Conclusion

In this way, we can also add circle and polygon in Google map.

History

  • 11th March, 2015: Initial version

License

This article, along with any associated source code and files, is licensed under The BSD License


Written By
Software Developer (Senior) icddr,b
Bangladesh Bangladesh
More than 8 years experience on Programming and Project implementation, I was primarily involved with projects for private organization,Govt.(Bangladesh Army,DG Health,RJSC), NGO (SEDF,WFP). Presently I am working at ICDDR,B and enhancing Hospital Management System developed by Microsoft Dynamic NAV and Windows Mobile Application 5.0

An active supporter of Open Source technology, my interested areas are ERP, IT Audit, Data warehouse, BI etc.

Playing Guitar for 15 years, my interested music style is Blues Rock,Neo Classical.

Certification

70-540:Microsoft® Windows Mobile® 5.0 - Application Development
MB7-514:Microsoft Dynamics™ NAV 5.0 C/SIDE Introduction
MB7-516:Microsoft Dynamics™ NAV 5.0 Solution Development
MB7-517:Microsoft Dynamics™ NAV 5.0 Installation and Configuration
MB7-515:Microsoft Dynamics™ NAV 5.0 Financials
70-432:Microsoft SQL Server 2008 - Implementation and Maintenance
70-450:PRO: Designing, Optimizing and Maintaining a Database Administrative Solution Using Microsoft SQL Server 2008
70-448:Microsoft SQL Server 2008, Business Intelligence Development and Maintenance
312-50:Certified Ethical Hacker

Web :http://masudparvezshabuz.appspot.com
Blog :http://masudparvezshabuz.wordpress.com
linkedin :http://www.linkedin.com/in/masudparvez

Comments and Discussions

 
Questiondisculpa, como adiciono una nueva etiqueta Pin
acurio20078-Aug-17 16:00
acurio20078-Aug-17 16:00 
Questionerro with me Pin
Member 126691936-Sep-16 4:09
Member 126691936-Sep-16 4:09 
GeneralGood Pin
Member 1110549025-Mar-15 17:46
Member 1110549025-Mar-15 17:46 
QuestionGood tutorial Pin
Member 1081629113-Mar-15 4:09
Member 1081629113-Mar-15 4:09 
QuestionMap Location Pin
Member 823122713-Mar-15 0:00
Member 823122713-Mar-15 0:00 
AnswerRe: Map Location Pin
mparvez13-Mar-15 4:39
mparvez13-Mar-15 4:39 
GeneralRe: Map Location Pin
Member 823122713-Mar-15 7:12
Member 823122713-Mar-15 7:12 
QuestionWhy did you use json? Pin
Gaurav Aroraa12-Mar-15 0:34
professionalGaurav Aroraa12-Mar-15 0:34 
AnswerRe: Why did you use json? Pin
mparvez12-Mar-15 4:02
mparvez12-Mar-15 4:02 
AnswerRe: Why did you use json? Pin
Gaurav Aroraa12-Mar-15 9:28
professionalGaurav Aroraa12-Mar-15 9:28 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.