Click here to Skip to main content
13,260,383 members (44,082 online)
Click here to Skip to main content
Add your own
alternative version

Stats

26K views
1.7K downloads
26 bookmarked
Posted 11 Mar 2015
BSD

Google Map with JSON

, 11 Mar 2015
Rate this:
Please Sign up or sign in to vote.
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.

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

Then add:

<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:

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.

[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.

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

Now Load Data in marker object.

Add Click event functionality in marker object.

Analysis of Server Side Code

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

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.

[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. </waliur.rahman@icddrb.org>

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

Share

About the Author

mparvez
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

You may also be interested in...

Comments and Discussions

 
Questiondisculpa, como adiciono una nueva etiqueta Pin
acurio20078-Aug-17 17:00
memberacurio20078-Aug-17 17:00 
Questionerro with me Pin
Member 126691936-Sep-16 5:09
memberMember 126691936-Sep-16 5:09 
GeneralGood Pin
Member 1110549025-Mar-15 18:46
memberMember 1110549025-Mar-15 18:46 
QuestionGood tutorial Pin
Member 1081629113-Mar-15 5:09
memberMember 1081629113-Mar-15 5:09 
QuestionMap Location Pin
Member 823122713-Mar-15 1:00
memberMember 823122713-Mar-15 1:00 
AnswerRe: Map Location Pin
mparvez13-Mar-15 5:39
membermparvez13-Mar-15 5:39 
GeneralRe: Map Location Pin
Member 823122713-Mar-15 8:12
memberMember 823122713-Mar-15 8:12 
QuestionWhy did you use json? Pin
Gaurav Kumar Arora12-Mar-15 1:34
professionalGaurav Kumar Arora12-Mar-15 1:34 
AnswerRe: Why did you use json? Pin
mparvez12-Mar-15 5:02
membermparvez12-Mar-15 5:02 
AnswerRe: Why did you use json? Pin
Gaurav Kumar Arora12-Mar-15 10:28
professionalGaurav Kumar Arora12-Mar-15 10: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.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.171114.1 | Last Updated 11 Mar 2015
Article Copyright 2015 by mparvez
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid