Click here to Skip to main content
Click here to Skip to main content

Show Your Data on Google Map using C# and JavaScript

By , 4 May 2009
 

Introduction

Almost every one of us who uses internet has seen the Google map, Google earth and Google street view, etc. The good thing is that Google also shares its products in a manner such that you can customize them according to your needs. In this article, I am going to share a simple technique to show your data on Google map.

Background

Previously, I wrote an article on how to count the visits and visitors on your website and save the data in a table including the IPs of the visitors. Then one day I visited a site that was offering to show similar data on Google map. I started to discover how I can do that if I have a database of IPs. I found that Google shares some Maps APIs that offer a lot of functionalities including placing a marker on the map if you can provide its coordinates, meaning the latitude and longitude of that point on the earth.

sampleMap.JPG

Now the only problem was that I had to translate the IP into its corresponding coordinates. I searched again and found some web services on the internet that can return the coordinates of an IP. That’s all I needed to know to achieve the goal and now it was just a matter of implementation.

How To Do That... Using the Code

Assuming that you have a table in a database that has two columns for earth coordinates you want to plot on Google map as shown below:

db.JPG

If you have a table that has IPs as in my previous article, you can add two new columns in that table, and then use some web services to update the table for coordinates manually or you can write a small program to call such a web service to update your database automatically. Or may be you want to show your shipments destinations on the map, or you might be interested in showing the location of showrooms of your products around the world and you have a similar data for that. Possibilities are endless.

Now how to plot this data on Google map? Google provides some API methods that you can call in JavaScript from your website and supply the coordinates to place a marker on the map. First you need to add the API's reference in your HTML in header tag as:

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

Note: You need to obtain a unique key for your site from Google before publishing your site. For test purposes on localhost you can use the above code as is.

Second, you have to place a div element in the page where you want to show the Google map, set its size, etc. according to your layout needs.

<div id="map_canvas" style="width: 100%; height: 728px; margin-bottom: 2px;">

Third, you can create a Google map object by passing it div element where you want to show the map.

var map = new GMap2(document.getElementById('map_canvas'));

Also you need to tell what location on the map should be in the center of map, first you get the point from Longitude and Latitude values. For example, if you want to see London in the center of the map, you can use method as:

GLatLng(51.5,-0.1167)

Now you can pass this point to setCenter method with zoom level of your map ranges from 1-20. I am using level 2 to see the whole world in my map, increasing this number will zoom the map to your center location.

map.setCenter(new GLatLng(51.5,-0.1167), 2);

Then you can specify a location on the map for Google to place a marker at that location by calling addOverlay method with GMarker object as argument that takes the actual coordinates of the location. For example to place a marker on Toronto, you can write the following line in the script.

map.addOverlay(new GMarker(new GLatLng(43.6667,-79.4168)));

You can specify as many markers as you want. Now you are ready to see the map. Put them all together in a JavaScript function and call it onload event of the page. The complete script will be something like:

<script type='text/javascript'>  
function initialize() {  
    if (GBrowserIsCompatible()) {  
        var map = new  Map2(document.getElementById('map_canvas'));      
        map.setCenter(new GLatLng(51.5,-0.1167), 2);       
        map.addOverlay(new  Marker(new GLatLng(43.6667,-79.4168)));      
        map.setUIToDefault();     
}   } </script> 

But wait a minute.. JavaScript! Isn’t it client side programming?... Then how can you pass the data to Google API from a database on your server? Right, this is the problem that you have to deal with. You need to use a combination of JavaScript and any server side scripting, e.g. ASP.NET C#, VB, PHP or CGI whichever suits your environment. I used C# and JavaScript to complete this.

You have to generate the JavaScript on the server for Google APIs and render it on the client by using an “asp:Literal” control . You also need to place a Div control on the page in which Google APIs can render a customized map in the browser and add reference to Google APIs script. So you only need two controls on your page a Literal and a Div. The complete HTML is shown below including Google API references for MAP.

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
   <title>Your Data on Google Map </title>
     <%--Google API reference--%>
     <script src="http://maps.google.com/maps? file=api&amp;
	v=2&amp;sensor=false&amp;key=abcdefg" type="text/javascript">
     </script>
</head><body onload="initialize()" onunload="GUnload()">
  <form id="form1" runat="server">
       <asp:Panel ID="Panel1" runat="server">
           <%--Place holder to fill with javascript by server side code--%>
           <asp:Literal ID="js" runat="server"></asp:Literal>
           <%--Place for google to show your MAP--%>
           <div id="map_canvas" style="width: 100%; height: 728px; 
		margin-bottom: 2px;">
           </div>
       </asp:Panel> 
</form>
</body> 
</html> 

Now how to create the script on the server that can show all of your markers on the map? Here is a method to do that. You need to pass it the table discussed above that has Longitude and Latitude values in two columns, for the points you want to mark on MAP and this method will generate the complete script with all map markers in the Literal control on the page.

private void BuildScript(DataTable tbl)
{
   String Locations = "";
   foreach (DataRow r in tbl.Rows)
    {
      // bypass empty rows 
       if (r["Latitude"].ToString().Trim().Length == 0)
           continue;

         string Latitude = r["Latitude"].ToString();
         string Longitude = r["Longitude"].ToString();

      // create a line of JavaScript for marker on map for this record 
       Locations += Environment.NewLine + " map.addOverlay
		(new GMarker(new GLatLng(" + Latitude + "," + Longitude + ")));";
   }

  // construct the final script
  js.Text = @"<script type='text/javascript'>
                  function initialize() {
                  if (GBrowserIsCompatible()) {
                     var map = new GMap2(document.getElementById('map_canvas'));
                    map.setCenter(new GLatLng(51.5,-0.1167), 2); 
                   " + Locations + @"
                  map.setUIToDefault();
                   }
               }
         </script> ";
} 

One you call this method in the *.cs file of your ASP form, it will create a complete JavaScript for Google to create a map and marker on your page.

Click here to see a live demo of this article. That site shows a marker on the map for each location from where any of my sites has been visited. If you have visited any of my sites, you should see a marker on your city on the map. Here is a snap of that demo site.

MyApp.JPG

For more details and usage of this article, you can visit my blog page about this article.

I have created a sample project for this article that you can download. It also has a sample access database in it. You can simply run this project in Microsoft Visual Studio 2008 without changing anything.

You can visit Google page about Maps APIs for more details about using and customizing Google Maps.

History

  • 4th May, 2009: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Ghaffar Khan
Software Developer (Senior)
Pakistan Pakistan
Member
I have been in the field of computer and IT for last eight years, after doing Masters in Computer Science from Karachi University.
 
My programing experience includes C/C++, C#, ASP.NET, PHP, Assembly Language, VC++, OpenGL, VB, FoxPro.
 
My Home City is Karachi. I love to see new places and never miss a chance to go out of the city whenever I get enough time.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
Hint: For improved responsiveness ensure Javascript is enabled and choose 'Normal' from the Layout dropdown and hit 'Update'.
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 4memberVassilisZenelis20 Nov '12 - 21:16 
QuestionGoogle Map Bind with sql server database.memberMudasirAbbasi16 Nov '12 - 23:53 
Answerneed help on interactive metro rail mapmemberdishantmudgal24 Feb '13 - 20:11 
GeneralMy vote of 5memberopik0745 Nov '12 - 16:58 
QuestionV3memberArief Aditya27 May '12 - 16:38 
QuestionHow to update map by adding markers in runtimememberankr02229 Apr '12 - 19:24 
Questionclick to show point namememberlionpag812 Nov '11 - 16:30 
QuestionHow can I show point names - Emergencymembersenarath.isuru23 Sep '11 - 2:45 
QuestionGet data from SQL Server databasememberartov5 Sep '11 - 3:04 
GeneralASCX Control <body onload="initialize()" onunload="GUnload()">membermacupryk11 Jul '11 - 9:56 
GeneralRe: ASCX Controlmembermacupryk11 Jul '11 - 9:56 
GeneralGoogle map APImemberMember 79328388 Jun '11 - 2:43 
GeneralMy vote of 5memberRakeshMeena24 May '11 - 20:45 
Questionınfo windowmemberresulguldibi22 Mar '11 - 12:31 
GeneralMy vote of 5memberbrendahdk13 Mar '11 - 18:51 
GeneralGREAT ARTICLE! THANK YOU VERY MUCH..memberKarag2723 Feb '11 - 3:05 
Questionhow to display address of coordinates on mapmembermaya saste4 Jan '11 - 1:21 
QuestionError for plotting large values in excelmemberFarah Siraj25 Nov '10 - 5:04 
Generaladding html to a marker on a map [modified]memberistoner18 Nov '10 - 17:53 
GeneralMy vote of 5memberisoint31 Oct '10 - 7:38 
GeneralMy vote of 5membervks1327 Oct '10 - 20:51 
Good example for using Google Map in ASP.Net.
 
Thanks
GeneralMy vote of 5memberAbhinav S19 Oct '10 - 4:25 
GeneralMultiple Divs for Same latitiude and longitudememberravindra_p27 Sep '10 - 21:24 
Generali cannot open the project in vs2008...membermasqazi18 Sep '10 - 21:02 
QuestionShow your data - zip code driven?memberparboy11 Jun '10 - 11:32 
QuestionPlease reply,i'm hardly in need of itmemberFarah Siraj10 Jun '10 - 9:48 
Generali have a VS 2005 versionmembersherazasad21 Apr '10 - 22:31 
GeneralRe: i have a VS 2005 versionmemberGhaffar Khan21 Apr '10 - 22:41 
GeneralNice way to connect things...memberEvoluteur16 Mar '10 - 20:59 
GeneralRe: Nice way to connect things...memberGhaffar Khan21 Apr '10 - 22:39 
Generalproblem in iplocation databasemembersidhusudhesh11 Feb '10 - 7:03 
GeneralThanks!memberMember 413487315 Oct '09 - 9:15 
GeneralRe: Thanks!memberGhaffar Khan21 Apr '10 - 22:38 
GeneralYou RockmemberMember 413487315 Oct '09 - 6:19 
GeneralRe: You RockmemberGhaffar Khan15 Oct '09 - 6:57 
GeneralVisual Studio 2005 versionmemberAbhishek_nmims7 Aug '09 - 21:36 
Questionhow to replace the markers with polylines ? please advisememberdreamerexe15 Jun '09 - 23:49 
GeneralShow MapmemberPhuc258321 May '09 - 20:50 
Generalsize of mapmemberrespirator12 May '09 - 5:47 
QuestionAll JavaScript?membercrb90005 May '09 - 9:29 
AnswerRe: All JavaScript?memberGhaffar Khan5 May '09 - 9:52 
JokeGreat JobmemberMember 28149635 May '09 - 8:40 
GeneralRe: Great JobmemberGhaffar Khan5 May '09 - 9:37 

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

Permalink | Advertise | Privacy | Mobile
Web02 | 2.6.130516.1 | Last Updated 4 May 2009
Article Copyright 2009 by Ghaffar Khan
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid