Friday, October 19, 2012

Google Maps Control for ASP.Net - Part 2

Google Maps Control for ASP.Net - Part 2

Free Open source Control

Google Map Control for ASP.Net

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

Google Map Control Logical 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.
    01.protected void Page_Load(object sender, EventArgs e)
    02.{
    03.//Specify API key
    04.GoogleMapForASPNet1.GoogleMapObject.APIKey =
    05.ConfigurationManager.AppSettings["GoogleAPIKey"];
    06. 
    07.//Specify width and height for map.
    08.GoogleMapForASPNet1.GoogleMapObject.Width = "800px";
    09.// You can also specify percentage(e.g. 80%) here
    10.GoogleMapForASPNet1.GoogleMapObject.Height = "600px";
    11. 
    12.//Specify initial Zoom level.
    13.GoogleMapForASPNet1.GoogleMapObject.ZoomLevel = 14;
    14. 
    15.//Specify Center Point for map.
    16.GoogleMapForASPNet1.GoogleMapObject.CenterPoint =
    17.new GooglePoint("1", 43.66619, -79.44268);
    18. 
    19.//Add pushpins for map.
    20.//This should be done with intialization of GooglePoint class.
    21.//In constructor of GooglePoint, First argument is ID of this pushpin.
    22.//It must be unique for each pin. Type is string.
    23.//Second and third arguments are latitude and longitude.
    24.GoogleMapForASPNet1.GoogleMapObject.Points.Add(
    25.new GooglePoint("1", 43.65669, -79.45278));
    26.}
  • 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.
    01.protected void Page_Load(object sender, EventArgs e)
    02.{
    03..
    04..
    05..
    06.if (!IsPostBack)
    07.{
    08.Session["GOOGLE_MAP_OBJECT"] = GoogleMapObject;
    09.}
    10.else
    11.{
    12.GoogleMapObject = (GoogleObject)Session["GOOGLE_MAP_OBJECT"];
    13..
    14..
    15..

    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 &ltDIV> element with ID=GoogleMap_Div. Google map is drawn on this &ltDIV> 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.
    1.Page.ClientScript.RegisterStartupScript(Page.GetType(), "onLoadCall", "
    2.if (window.DrawGoogleMap) { DrawGoogleMap(); }
    3.");

    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.
    01.[WebMethod(EnableSession = true)]
    02.public GoogleObject GetGoogleObject()
    03.{
    04.GoogleObject objGoogle = 
    05.(GoogleObject)System.Web.HttpContext.Current.Session["GOOGLE_MAP_OBJECT"];
    06. 
    07.System.Web.HttpContext.Current.Session["GOOGLE_MAP_OBJECT_OLD"] =
    08.new GoogleObject(objGoogle);
    09.return objGoogle;
    10.}

    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.
    1. 
    When &ltServiceReference> is used with &ltScriptManagerProxy> or &ltScriptManager> 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.
    01.function DrawGoogleMap()
    02.{
    03.if (GBrowserIsCompatible())
    04.{
    05.map = new GMap2(document.getElementById("GoogleMap_Div"));
    06.geocoder = new GClientGeocoder();
    07. 
    08.GService.GetGoogleObject(fGetGoogleObject);
    09.}
    10.}

    GService.GetGoogleObject() is a web service method. fGetGoogleObject() is a javascript function that should be called once web service method returns.
    01.function fGetGoogleObject(result, userContext)
    02.{
    03.map.setCenter(new GLatLng(result.CenterPoint.Latitude,
    04.result.CenterPoint.Longitude), result.ZoomLevel);
    05. 
    06.if(result.ShowMapTypesControl)
    07.{
    08.map.addControl(new GMapTypeControl());
    09.}
    10..
    11..
    12..

    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,
    01.function endRequestHandler(sender, args)
    02.{
    03.GService.GetOptimizedGoogleObject(fGetGoogleObjectOptimized);
    04.}
    05.function pageLoad()
    06.{
    07.if(!Sys.WebForms.PageRequestManager.getInstance().get_isInAsyncPostBack())
    08.Sys.WebForms.PageRequestManager.getInstance().add_endRequest(endRequestHandler);
    09.

    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..
  • 01.function CreateMarker(point,icon1,InfoHTML,bDraggable,sTitle)
    02.{
    03.var marker;
    04.marker = new GMarker(point,{icon:icon1,draggable:bDraggable,title: sTitle});
    05.if(InfoHTML!='')
    06.{
    07.GEvent.addListener(marker, "click", function() { this.openInfoWindowHtml(InfoHTML); });
    08.}
    09.GEvent.addListener(marker, "dragend", function() { 
    10.GService.SetLatLon(this.value,this.getLatLng().y,this.getLatLng().x);
    11.RaiseEvent('PushpinMoved',this.value);  });
    12.return marker;
    13.}

    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.
    1.function RaiseEvent(pEventName,pEventValue)
    2.{
    3.document.getElementById('').value = pEventName;
    4.document.getElementById('').value = pEventValue;
    5.__doPostBack('UpdatePanel1','');
    6.}

    When postback finishes, new latitude and longitude values will be picked up from Session Variable.
  • 1.function RecenterAndZoom(bRecenter,result)

    This function causes Recentering of map. It finds all visible markers on map and decides center point and zoom level based on these markers.
  • 1.function CreatePolyline(points,color,width,isgeodesic)

    This function creates polylines between given points. See Polylines property in GoogleObject class.
  • 1.function CreatePolygon(points,strokecolor,strokeweight,strokeopacity,fillcolor,fillopacity)

    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.
    01..
    02..
    03.myIcon_google = new GIcon(G_DEFAULT_ICON);
    04.markerOptions = { icon:myIcon_google };
    05. 
    06.myIcon_google.iconSize = new GSize(result.Points[i].IconImageWidth,
    07.result.Points[i].IconImageHeight);
    08.myIcon_google.image = result.Points[i].IconImage;
    09.myIcon_google.shadow = result.Points[i].IconShadowImage;
    10.myIcon_google.shadowSize = new GSize(result.Points[i].IconShadowWidth,
    11.result.Points[i].IconShadowHeight);
    12.myIcon_google.iconAnchor =  new GPoint(result.Points[i].IconAnchor_posX,
    13.result.Points[i].IconAnchor_posY);
    14.myIcon_google.infoWindowAnchor = new GPoint(result.Points[i].InfoWindowAnchor_posX,
    15.result.Points[i].InfoWindowAnchor_posY);
    16..
    17..
  • 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

No comments:

Post a Comment