Google Maps Control for ASP.Net - Part 2
- Details
- Category: ASP.Net
- Published on Sunday, 17 April 2011 04:41
- Written by Shabdar
- Hits: 12911
Free Open source Control

Introduction
This is second part in two part series of my article Google Maps User Control for ASP.Net. In first part Google Maps Control for ASP.Net - Part 1 I have explained how to use this control in your ASP.Net application. In this part I am going to explain source code of this user control so that you can modify it for your own use.
Diagram

Diagram above shows working flow of this user control. I will explain you one by one each element in this diagram.
ASPX page with Google Map User Control
- As I mentioned in part 1, we need to initialize few properties of this user control to make it work. These properties are initialized in Page_Load() event of ASPX page.
- When you initialize these properties, they gets stored in GOOGLE_MAP_OBJECT session variable. Later on this session variable is accessed by GService.asmx web service to draw google map.
- Go to source of GoogleMapForASPNet.aspx.cs file. Check Page_Load() method.
As you can see, I am storing GoogleMapObject property in a session variable if this is a first time load of page. If this is a post back then I use existing session variable value and assign it to GoogleMapObject property.
User Control (GoogleMapForASPNet.ascx)
- GoogleMapForASPNet.ascx file contains a <DIV> element with ID=GoogleMap_Div. Google map is drawn on this <DIV> element
- GoogleMapForASPNet.ascx is responsible for calling DrawGoogleMap() javascript function on page load. If you see source of GoogleMapForASPNet.ascx.cs file, it contains following lines in Page_Load() event.
This causes DrawGoogleMap() function to get fired.
GoogleMapAPIWrapper.js
- This javascript acts as a wrapper between ASP.Net calls and Google Maps Core API functions.
- When DrawGoogleMap() function is called, it calls web service method GService.GetGoogleObject() to get session variable values.
- Once different parameters are retrieved from session variable, it will start calling Google Maps core API functions to draw a map.
Web Service (GService.asmx)
- As I have mentioned before, GService.GetGoogleObject() and GService.GetGoogleObjectOptimized() are functions defined in GService.asmx file.
- These functions retrieves Google Map parameters from session variable.
How to define a Web Service Method
- This control uses Web Service Methods to get values from a session variable. These methods are defined in Gservice.cs(GService.asmx code behind) file.
- Go to source of GService.cs file. Observe how GetGoogleObject() web method is defined.
Return value type from this method is GoogleObject.
How to call ASP.Net function (Web service method) from Javascript using a Web Service
- If you go to HTML source of GoogleMapForASPNet.ascx file, you will see that I am using <ScriptManagerProxy> control.
When <ServiceReference> is used with <ScriptManagerProxy> or <ScriptManager> controls, it allows you to use web service methods defined in code behind. - Go to source of GoogleMapAPIWrapper.js file. Observe how I am calling a web service method in DrawGoogleMap() function.
GService.GetGoogleObject() is a web service method. fGetGoogleObject() is a javascript function that should be called once web service method returns.
result is return value from web service method GService.GetGoogleObject(). Thus result is of type GoogleObject. You can access properties of result in javascript to get map parameters.
Difference between GetGoogleObject() and GetGoogleObjectOptimized()
- Both of these methods work in similar fashion. GetGoogleObject() is called when page loads for first time. It returns all of the GoogleObject properties to javascript function. While GetGoogleObjectOptimized is called on postback. It does not return all of the properties. Instead it returns minimum properties required to make a change in existing map.
- If you view source of GoogleMapAPIWrapper.js file, there are two functions defined in it as below,
These function causes GService.GetOptimizedGoogleObject() to get fired when an AJAX call finishes. For example let's say you have a button in an UpdatePanel. When you click it, it postbacks the page. When this postback completes, above function will get fire.
Functions defined in GoogleMapAPIWrapper.js
- To make this article short, I don't want to explain each and every function defined in this file. Instead I will explain important functions only. If you want more details for any code that's not explained here, you can post your questions in Comments section..
-
This function creates a marker on Google Map. As you can see, I am adding two events with each marker. First one is click(). When a user clicks on marker, a balloon (info window) pops up. This is a javascript event. Second one is dragend(). If a user wants he can drag a pushpin to a new location. This will cause a web method GService.SetLatLon() to get executed. This method sets new latitude and longitude values in Session Variable. As you can see this function also calls RaiseEvent() function which causes an AJAX postback.
When postback finishes, new latitude and longitude values will be picked up from Session Variable. -
This function causes Recentering of map. It finds all visible markers on map and decides center point and zoom level based on these markers. -
This function creates polylines between given points. See Polylines property in GoogleObject class. -
This function creates polygons between given points. See Polygons property in GoogleObject class.
How to define Icons for google map
- If you see implementation of fGetGoogleObject() and fGetGoogleObjectOptimized() javascript functions, you can see that I am creating custom icons for google map. This is how they are defined.
- There are various properties that you can set for a custom icon. Following article explains you each of these properties in detail.
Making your own custom markers
Special Notes
I have published this article on www.codeproject.com as well. Here is the link to this article.
Google Maps Control for ASP.Net - Part 1
Comments/Questions
|
Thank you very much for this great web user control.
I have a one question here, how can i put some pins on client click. For example i want users to put only one pin on the map and there will be a save marker button when the user clicks on the button, the coordinates will be saved in database. Thanks => Barbaros (Thursday 05-Jun-08 05:40 AM)
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
First, Thanks for a Nice collection of code.
But, when I use "MapWithDraggableIcons" I gets a Error in the following function: Is Says "document.getElementById('')" dont return a valid Object. I look forward to hear from you. Regads Thomas. function RaiseEvent(pEventName,pEventValue) { document.getElementById('').value = pEventName; document.getElementById('').value = pEventValue; __doPostBack('UpdatePanel1',''); => Thomas Olsen (Sunday 08-Jun-08 05:51 AM)
Hi Shabdar,
I upgraded to your new v1.5 control, so far it looks great. In v.1.4 I had added G_PHYSICAL_MAP map type, enableDoubleClickZoom, and enableScrollWheelZoom, and all worked great. I moved my code changes over into the new GoogleMapAPIWrapper,js file (see below) but none of the functions work now. Any ideas? Chris // Add the Terrain map type map.addMapType(G_PHYSICAL_MAP); map.setMapType(eval(result.MapType)); // Add zoom via mouse double click map.enableDoubleClickZoom(); // Add zoom via mouse scroll wheel map.enableScrollWheelZoom(); => Chris Mangiapane (Wednesday 11-Jun-08 12:14 AM)
When I send parameters to a aspx file this mymap.aspx?id=2
I got a Decode error in s = System.Web.HttpContext.Current.Request.MapPath(PageName).Split(new char[] { '' }); Becayse Pagename include th "?id=2" I have changed this to solv the problem in cGoogleMap.cs: public static string GetLocalPath() { string[] s = System.Web.HttpContext.Current.Request.Url.AbsoluteUri.Split(new char[] { '/' }); string PageName = s[s.Length - 1]; int PageNameLength = PageName.IndexOf("?"); // New if (PageNameLength != -1) // New { // New PageName = PageName.Substring(0, PageNameLength); } // New s = System.Web.HttpContext.Current.Request.MapPath(PageName).Split(new char[] { '' }); string path = s[0] + ""; for (int i = 1; i < s.Length - 1; i++) { path = path + s[i] + ""; } return path; I hope you will aplly this to your code base ! => Thomas Olsen (Wednesday 11-Jun-08 01:58 AM)
Is there a way to put a hyperlink inside the InfoHTML html text that contains javascript to fire a server-side event?
I one to add a 'Select' link in the InfoHTML. When clicked, it should fire a server-side event with that marker's information sent to the code-behind, so the server can change the marker icon and redraw the map. Sure would appreciate a small example; I've been struggling with this one for days. Chris => Chris Mangiapane (Saturday 14-Jun-08 08:36 PM)
GetLocalPath() in cGoogleMap.cs doesn't handle URLs with query strings.
ex: 'locate_dealer.aspx?zipcode=02360' is not a valid virtual path. I did a second split on the ? to fix it. => Steve (Monday 16-Jun-08 08:31 AM)
Hey, this is very useful and i love that you can dynamically set the push pins by longitude and latitude, but is there a way of setting them by a postcode? Or is there a simple way of getting the longitude and latitude values from a postcode?
Help with this would be invaluable. Thanks Si! => Simon Caine (Sunday 22-Jun-08 09:57 PM)
Hi
In denmark we use "," as the default seperator, but the converter function use systemet setting, it must be hardcodet to use "." as Seperator. I made a small addon to Code: public static double GetNumericValue(object pNumValue) { if ((pNumValue == null)) { return 0; } System.Globalization.NumberFormatInfo GoogleFormat = new System.Globalization.NumberFormatInfo(); // New GoogleFormat.NumberDecimalSeparator = "."; // New if (IsNumeric(pNumValue)) { return double.Parse((pNumValue.ToString()), GoogleFormat); // Updated. } else { return 0; } I hope you will use this in next release, or make your own type of code ;) => Thomas Olsen (Monday 23-Jun-08 05:36 AM)
I was hoping you'd show how to read an SQL table and get the Lng/Lat data as pushpins into your maps... Thank you!
=> Brian (Tuesday 24-Jun-08 03:08 PM)
Is it possible to hide the map control on the page and then show it on the click of a Button ?
This button would be in another UpdatePanel on the same Page. I tried it, but ran into a problem where the UpdatePanelXXXYYY could not be found (I don't know the exact message right now) ? Regards, Geert Veenstra => Geert Veenstra (Wednesday 25-Jun-08 11:06 PM)
Hi Shabdar
Has anyone taken a look a the GStreetviewOverlay in order to provide a map 'street view'? Here is a nice glimpse at what it can do: http://googlemapsapi.blogspot.com/2008/03/street-view-in-api-or-how-i-spent-my.html Any plans to add this in upcoming versions? => Chris Mangiapane (Wednesday 02-Jul-08 11:01 AM)
I have a requirement as:
I want to add a Plane Map of India on a aspx Page. It should only show states boundaries. On clicking of a particular state it should get highlighted and i want to show some further information pertaining to that state, which is stored in database. How can i do that in visual studio 2005. => Gaurav (Thursday 03-Jul-08 12:29 AM)
Is it possible to use the Google Maps Control in SQL Server Reporing services 2005?
I have stored the coordinates in the DB and to jump to an URL. The parameter ( coordinates, Text ) should be transferd over the Hyperlink Address. Or is there an other way ? => Peda (Thursday 03-Jul-08 07:10 AM)
HI,
I downloaded your component, started up VS2008 after updating to 3.5 the application run quite well. I then tried the setup steps outlined above to create a new project and on build received a message that I was missing a Script Manager. I added one and the result was a blank page. Do you have any suggestions on how to get started so that the default map displays? Thanks In Advance, James => James Hein (Thursday 10-Jul-08 01:50 AM)
Great article!I have to remember the latitude and longitude of the icons in sql table.I did it,but with one error,which come very rare.When I drag one icon everything is ok.But when I have two or more icons when i am dragging some of them the dragged before the last go to the "old" place and in the table the "old coordinates" are stored.But the last is stored with new coordinates.I can't understand why.
=> stefan (Friday 11-Jul-08 05:51 AM)
Hi again!I have another question.I make my error,but i have one question about the service.
public void SetLatLon(string pID, double pLatitude, double pLongitude) { GoogleObject objGoogleNew = (GoogleObject)System.Web.HttpContext.Current.Session["GOOGLE_MAP_OBJECT"]; GoogleObject objGoogleOld = (GoogleObject)System.Web.HttpContext.Current.Session["GOOGLE_MAP_OBJECT_OLD"]; objGoogleNew.Points[pID].Latitude = pLatitude; objGoogleNew.Points[pID].Longitude = pLongitude; //objGoogleOld.Points[pID].Latitude = pLatitude; //objGoogleOld.Points[pID].Longitude = pLongitude; } I marked this two lines an everything is ok.What is the purpose of them. I marked them because i think that the GetOptimizedGoogleObject() can't understand about the changet point location. => stefan (Friday 11-Jul-08 09:15 AM)
Is it possible to use this in a Web Application VS2005? I have spent quite a few hours trying. First I recieved the GService is undefined error and seam to have gotten past that by adding Inline scripts = true
But now I get Error: no element found Source File: http://localhost/website/GService.asmx/GetGoogleObject Line: 1 I see the div with the Google logo on the bootom but no map Any ideas would be appreciated => Dave (Tuesday 15-Jul-08 07:46 PM)
Have you thought about incorporating this?
"If you have an existing Maps API site, you can 3D-enable your page with as little as one line of code." => Brian (Wednesday 16-Jul-08 09:36 AM)
I noticed the following behavior in your example "Google Map with Draggable pushpins"
when you zoom in and move the pushpin to a new location the map will zoom out to the original zoom level. Is there a way to keep it from doing that? I have tried to set the zoomlevel (GoogleMapForASPNet1.GoogleMapObject.ZoomLevel) to different values in different places of the script - load page area (doesnt seem to change the zoomlevel) - in OnPushpinMoved It seems that it still will go back to the original zoomlevel Any suggestions how to fix this? Thanks for a nice google map control => Islandhopper8 (Saturday 19-Jul-08 12:33 PM)
Hi,
I am facing the problem to draw Poly line on the GMap. i.e I am able to draw up to 15 Lan&Lat values, if above I am not able to draw line dynamically. Here I am retrieving the Lag & Lat values dynamically from Sql-Server. Even here I am mentioning the error which I am getting…. Microsoft JScript runtime error: Sys.Net.WebServiceFailedException: The server method 'GetGoogleObject' failed with the following error: System.InvalidOperationException-- Error during serialization or deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set on the maxJsonLength property. Thanks & Regards, Hanu => Hanu (Monday 21-Jul-08 08:42 AM)
Hi all!
I need help.I am not familiar with Javascript and want to ask something about Polylines.Can i create a InfoHTML for a polyline,when it is clicked or mouseover to show some info? Thanks => stefoto (Monday 21-Jul-08 09:19 AM)
I just wanted to say that I enjoyed reviewing and using this control. I have successfully implemented it with minor changes. A previous post mentioned having to change the "GetLocalPath" function. However, it didn't work so I changed it to the following which fixed it.
public static string GetLocalPath() { string[] s = System.Web.HttpContext.Current.Request.Url.AbsoluteUri.Split(new char[] { '/' }); string PageName = s[s.Length - 1]; int PageNameLength = PageName.IndexOf("?"); if (PageNameLength != -1) { PageName = PageName.Substring(0, PageNameLength); } s = System.Web.HttpContext.Current.Request.MapPath(PageName).Split(new char[] { '//' }); //NEW because '' is not valid char string path = s[0] + ""; //places proper backslashes for (int i = 1; i < s.Length - 1; i++) { path = path + s[i] + ""; // new } return path; => brent (Monday 28-Jul-08 10:37 AM)
Do you do any custom development? I have a Google Maps project I would like to be completed.
Thanks, Steve => Steve (Monday 04-Aug-08 10:45 AM)
Hi;
Thanks for the great control. I wonder if i can get geocodes of any point i click on the map. => Burak (Friday 15-Aug-08 09:52 AM)
Hi Shabdar. Great google map control but there is a runtime error if i use this control with the browsers(IE,FF).
I downloaded the newest Version from here: downloads/GoogleMapControl.zip If i click one time with the right mouse button on the map, this runtime error appears: line: 784 Error: 'this.ff.width' is Null or not an object This is the line (main.js): Uj.prototype.Ow=function(a){return new N(a.x+this.ff.width,a.y+this.ff.height)}; Thanks, => Quang (Thursday 21-Aug-08 03:15 AM)
Hi there, looks to be a great control but I can't seem to get your control to work.
if (hidEventName.Value == "PushpinMoved") { //Set event name to blank string, so on next postback same event doesn't fire again. hidEventName.Value = ""; OnPushpinMoved(hidEventValue.Value); This line doesn't seem to work, sine the hidEventName is in the contentTemplate, so it can't be accessed, or am I doing something wrong? Cheers, Sarkie. => Sarkie (Friday 22-Aug-08 04:06 AM)
thank you
=> xna (Wednesday 03-Sep-08 09:39 AM)
hi.,
*I am having some problems in writing to databases... can u show me a sample test page where database connection is used and the database design too.. *is it possible for me to convert a text file with lat and lang to a organized XML file. thanks => hussain (Thursday 04-Sep-08 02:39 AM)
Thank You very much for your great control,I want to say that it
is the greatest one as I ever seen before.you save my life,you are the god. => intrepid (Friday 05-Sep-08 12:43 AM)
H! Great article.
I have two questions.1-Can I use this without webservice? and 2-I want a image from DBase along with text to b displayed in a bubble that comes when user click the pin. For first question I tried to write methods in the code-behind file and using "PageMethods" I called them from javascript.Functions get called ,but with some script errors. Can you comment on it please. => Nirav (Thursday 11-Sep-08 12:09 AM)
One More Problem
When I add more(50+) points on map it takes too long to get loaded. What to do when we have thousands of loactions to be pointed on the map. => Nirav (Thursday 11-Sep-08 02:55 AM)
Thanks for a great control. In my part of the world (Kenya) we get some pretty lousy internet connections. When a connection fails partway the javascript fails at
if(GBrowserIsCompatible()) Now I can either move this into a try..catch block, or test that the function is instantiated first with if(GBrowserIsCompatible) I need to bubble this error up into an error event for the control that I can handle in the calling program. The problem is that what I know about JavaScript is dangerous and I'd be very grateful for any suggestions you may have. Regards Bob Morris => Bob Morris (Wednesday 17-Sep-08 01:47 PM)
This thing is awsome!!! Thank you so much. The only thing I am missing is Street View. Anyway to do this?
=> Dale (Thursday 25-Sep-08 08:53 AM)
First of all, great article. I have a question about Geocoding. I keep getting a 'request timed out' error when entering Seattle, WA in the GooglePoint address property. Its pretty much straight from the sample. Perhaps I'm doing something wrong. Any suggestions?
=> Sancho (Tuesday 07-Oct-08 03:23 PM)
Hi, you made a great job... It's very usefull control. But i've got a question, i try to get the ID of a point when i click on it to show it in a label...As you do with the pushpin moved. Is there a way to get back and handle the informations from the bubble???? Please answer me if you have any idea or anyone else got any idea...
Thank you. => panos (Wednesday 19-Nov-08 07:10 AM)
If I want to display a point's infoHTML by default, how would I do that? Whenever a point has some infoHTML, it should be displayed. How this can be done?
=> Sanket Apte (Saturday 29-Nov-08 11:51 PM)
Thank you very much for this great web user control.
How do I plot routemap or polyline based on some langitude and longitude values in a looop. Any one please advice or guide me to any URL...of doumentation please.. thanks venky => venky (Tuesday 02-Dec-08 12:58 PM)
Dear Shabdar,
Thanks for the great control.... I've got some queries... How can I get the Latitude & Longitude of a point clicked on the map. Thanks, Yogesh J S => Yogesh (Wednesday 03-Dec-08 03:14 AM)
I was wondering if you have worked on the getBounds or adding the ability to get directions yet?
Charles => Charles Ralston (Thursday 04-Dec-08 02:51 PM)
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||


