Click here to Skip to main content
15,881,715 members
Articles / Web Development / ASP.NET
Article

Google Maps Control for ASP.NET - Part 2

Rate me:
Please Sign up or sign in to vote.
4.56/5 (17 votes)
4 Jun 2008GPL35 min read 162.2K   78   37
Discusses the source of this User Control.

Image 1

Introduction

This is the second part in a two part series of my article, Google Maps User Control for ASP.NET. In the 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 the source code of this user control so that you can modify it for your own use.

Diagram

Image 2

The diagram above shows the working flow of this user control. I will explain to you one by one each element in this diagram.

ASPX page with the Google Map User Control

  • As I mentioned in part 1, we need to initialize a few properties of this user control to make it work. These properties are initialized in the Page_Load() event of the ASPX page.
  • C#
    protected void Page_Load(object sender, EventArgs e)
    {
        //Specify API key
        GoogleMapForASPNet1.GoogleMapObject.APIKey = 
                    ConfigurationManager.AppSettings["GoogleAPIKey"]; 
    
        //Specify width and height for map.
        GoogleMapForASPNet1.GoogleMapObject.Width = "800px"; 
        // You can also specify percentage(e.g. 80%) here
        GoogleMapForASPNet1.GoogleMapObject.Height = "600px";
    
        //Specify initial Zoom level.
        GoogleMapForASPNet1.GoogleMapObject.ZoomLevel = 14;
    
        //Specify Center Point for map. 
        GoogleMapForASPNet1.GoogleMapObject.CenterPoint = 
                        new GooglePoint("1", 43.66619, -79.44268);
    
        //Add pushpins for map.
        //This should be done with intialization of GooglePoint class.
        //In constructor of GooglePoint, First argument is ID of this pushpin. 
        //It must be unique for each pin. Type is string.
        //Second and third arguments are latitude and longitude.
        GoogleMapForASPNet1.GoogleMapObject.Points.Add(
                                new GooglePoint("1", 43.65669, -79.45278));
    }
  • When you initialize these properties, they gets stored in the GOOGLE_MAP_OBJECT session variable. Later on, this session variable is accessed by the GService.asmx web service to draw the Google map.
  • Go to the GoogleMapForASPNet.aspx.cs file. Check the Page_Load() method.
  • C#
    protected void Page_Load(object sender, EventArgs e)
    {
        .
        .
        .
        if (!IsPostBack)
        {
            Session["GOOGLE_MAP_OBJECT"] = GoogleMapObject;
        }
        else
        {
            GoogleMapObject = (GoogleObject)Session["GOOGLE_MAP_OBJECT"];
            .
            .
            .

    As you can see, I am storing the GoogleMapObject property in a session variable if this is the first time load of the page. If this is a post back, then I use the existing session variable value and assign it to the GoogleMapObject property.

User Control (GoogleMapForASPNet.ascx)

  • The GoogleMapForASPNet.ascx file contains a <DIV> element with ID=GoogleMap_Div. The Google map is drawn on this <DIV> element
  • GoogleMapForASPNet.ascx is responsible for calling the DrawGoogleMap() JavaScript function on page load. If you look in the GoogleMapForASPNet.ascx.cs file, it contains the following lines in the Page_Load() event:
  • C#
    Page.ClientScript.RegisterStartupScript(Page.GetType(), 
       "onLoadCall", "<script language="'javascript'"> " + 
       "if (window.DrawGoogleMap) { DrawGoogleMap(); } </script>");

    This causes the DrawGoogleMap() function to get fired.

GoogleMapAPIWrapper.js

  • This JavaScript acts as a wrapper between the ASP.NET calls and the Google Maps Core API functions.
  • When the DrawGoogleMap() function is called, it calls the web service method GService.GetGoogleObject() to get the session variable values.
  • Once different parameters are retrieved from the session variable, it will start calling the Google Maps core API functions to draw a map.

Web Service (GService.asmx)

  • As I have mentioned before, GService.GetGoogleObject() and GService.GetGoogleObjectOptimized() are the functions defined in the GService.asmx file.
  • These functions retrieve Google Map parameters from the 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 the Gservice.cs (GService.asmx code-behind) file.
  • Go to the GService.cs file. Observe how the GetGoogleObject() web method is defined.
  • C#
    [WebMethod(EnableSession = true)]
    public GoogleObject GetGoogleObject()
    {
        GoogleObject objGoogle =  
            (GoogleObject)System.Web.HttpContext.Current.Session["GOOGLE_MAP_OBJECT"];
    
        System.Web.HttpContext.Current.Session["GOOGLE_MAP_OBJECT_OLD"] = 
                                                          new GoogleObject(objGoogle);
        return objGoogle;
    }

    Return the value type from this method as GoogleObject.

How to call an ASP.NET function (Web Service method) from JavaScript using a Web Service

  • If you go to the HTML source of the GoogleMapForASPNet.ascx file, you will see that I am using a <ScriptManagerProxy> control.
  • ASP.NET
    <asp:ScriptManagerProxy ID="ScriptManager1" runat="server">
     <Services>
        <asp:ServiceReference Path="~/GService.asmx" />
      </Services>
    </asp:ScriptManagerProxy>

    When <ServiceReference> is used with <ScriptManagerProxy> or <ScriptManager> controls, it allows you to use Web Service methods defined in the code-behind.

  • Go to the GoogleMapAPIWrapper.js file. Observe how I am calling a Web Service method in the DrawGoogleMap() function.
  • JavaScript
    function DrawGoogleMap()
    {
        if (GBrowserIsCompatible())
        {
          map = new GMap2(document.getElementById("GoogleMap_Div"));
          geocoder = new GClientGeocoder();
      
          GService.GetGoogleObject(fGetGoogleObject);
        }
    }

    GService.GetGoogleObject() is a web service method. fGetGoogleObject() is a javascript function that should be called once web service method returns.

    JavaScript
    function fGetGoogleObject(result, userContext)
    {
        map.setCenter(new GLatLng(result.CenterPoint.Latitude, 
                      result.CenterPoint.Longitude), result.ZoomLevel);
        
        if(result.ShowMapTypesControl)
        {
            map.addControl(new GMapTypeControl());
        }
        .
        .
        .

    The result is the return value from the Web Service method GService.GetGoogleObject(). Thus, result is of type GoogleObject. You can access the properties of result in JavaScript to get the map parameters.

Difference between GetGoogleObject() and GetGoogleObjectOptimized()

  • Both of these methods work in a similar fashion. GetGoogleObject() is called when the page loads for the first time. It returns all of the GoogleObject properties to the JavaScript function. GetGoogleObjectOptimized is called on postback. It does not return all of the properties. Instead, it returns the minimum properties required to make a change in the existing map.
  • If you view the GoogleMapAPIWrapper.js file, there are two functions defined in it as shown below:
  • JavaScript
    function endRequestHandler(sender, args)
    {
        GService.GetOptimizedGoogleObject(fGetGoogleObjectOptimized);
    }
    function pageLoad()
    {
        if(!Sys.WebForms.PageRequestManager.getInstance().get_isInAsyncPostBack())
            Sys.WebForms.PageRequestManager.getInstance().add_endRequest(endRequestHandler);
    }

    These functions cause the 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, the above function will get fired.

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 the important functions only. If you want more details of any code that's not explained here, you can post your questions in the Comments section..

JavaScript
function CreateMarker(point,icon1,InfoHTML,bDraggable,sTitle)
{
    var marker;
    marker = new GMarker(point,{icon:icon1,draggable:bDraggable,title: sTitle});
    if(InfoHTML!='')
    {
        GEvent.addListener(marker, "click", 
               function() { this.openInfoWindowHtml(InfoHTML); });
    }
    GEvent.addListener(marker, "dragend", function() {  
            GService.SetLatLon(this.value,this.getLatLng().y,this.getLatLng().x);
            RaiseEvent('PushpinMoved',this.value);  });
    return marker;
}

This function creates a marker on the Google map. As you can see, I am adding two events with each marker. The first one is click(). When a user clicks on a marker, a balloon (info window) pops up. This is a JavaScript event. The 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 the new latitude and longitude values in the Session variable. As you can see, this function also calls the RaiseEvent() function which causes an AJAX postback.

JavaScript
function RaiseEvent(pEventName,pEventValue)
{
    document.getElementById('<%=hidEventName.ClientID %>').value = pEventName;
    document.getElementById('<%=hidEventValue.ClientID %>').value = pEventValue;
    __doPostBack('UpdatePanel1','');
}

When the postback finishes, the new latitude and longitude values will be picked up from the Session variable.

JavaScript
function RecenterAndZoom(bRecenter,result)

This function causes re-centering of the map. It finds all the visible markers on the map and decides the center point and the zoom level based on these markers.

JavaScript
function CreatePolyline(points,color,width,isgeodesic)

This function creates polylines between the given points. See the Polylines property in the GoogleObject class.

JavaScript
function CreatePolygon(points,strokecolor,strokeweight, 
                       strokeopacity,fillcolor,fillopacity)

This function creates polygons between the given points. See the Polygons property in the GoogleObject class.

How to define icons for the Google map

  • If you see the implementation of the fGetGoogleObject() and fGetGoogleObjectOptimized() JavaScript functions, you can see that I am creating custom icons for the Google map. This is how they are defined:
  • JavaScript
    .
    .
    myIcon_google = new GIcon(G_DEFAULT_ICON);
    markerOptions = { icon:myIcon_google };
    
    myIcon_google.iconSize = new GSize(result.Points[i].IconImageWidth,
                                        result.Points[i].IconImageHeight);
    myIcon_google.image = result.Points[i].IconImage;
    myIcon_google.shadow = result.Points[i].IconShadowImage;
    myIcon_google.shadowSize = new GSize(result.Points[i].IconShadowWidth, 
                                            result.Points[i].IconShadowHeight);
    myIcon_google.iconAnchor =  new GPoint(result.Points[i].IconAnchor_posX, 
                                        result.Points[i].IconAnchor_posY);
    myIcon_google.infoWindowAnchor = new GPoint(result.Points[i].InfoWindowAnchor_posX, 
                                    result.Points[i].InfoWindowAnchor_posY);
    .
    .
  • There are various properties that you can set for a custom icon. The following article explains each of these properties in detail: Making your own custom markers.

Special notes

I have published this article on my blog as well. Here is the link to the article: Google Maps Control for ASP.NET - Part 2.

License

This article, along with any associated source code and files, is licensed under The GNU General Public License (GPLv3)



Comments and Discussions

 
Questionproblem using GoogleMapForASPNet control in a webform solution Pin
Member 110082596-Feb-15 4:42
Member 110082596-Feb-15 4:42 
AnswerRe: problem using GoogleMapForASPNet control in a webform solution Pin
Member 1100825925-Feb-15 8:40
Member 1100825925-Feb-15 8:40 
QuestionGoogle Maps - Part 2 Code link and Blog link is broken. Pin
TomLeonard10-Dec-14 7:00
professionalTomLeonard10-Dec-14 7:00 
QuestionProblem when Publish on Virtual Server Pin
pablodecker16-Sep-14 2:13
pablodecker16-Sep-14 2:13 
QuestionPolyline Click Event Pin
huynhle300526-Jun-14 4:41
huynhle300526-Jun-14 4:41 
GeneralThe map shows a very shortly-gray scale refresh into the EEUU map Pin
Lechu8110-Feb-14 8:28
Lechu8110-Feb-14 8:28 
QuestionHow to click on the mao and get a pin? Pin
Member 975229113-Jan-13 4:41
Member 975229113-Jan-13 4:41 
QuestionGoogle Map Control Pin
Naresh Mittal29-Oct-12 11:32
Naresh Mittal29-Oct-12 11:32 
Questionlabeled markers Pin
Salahov1-Sep-12 12:35
Salahov1-Sep-12 12:35 
QuestionShow information popup of marker on click of button out side the map Pin
Netweb23-Aug-12 1:59
Netweb23-Aug-12 1:59 
QuestionMap service Pin
Suraj S Koneri12-Apr-12 20:10
Suraj S Koneri12-Apr-12 20:10 
QuestionZoomLevel still not responsive Pin
rowek5-Apr-12 3:17
rowek5-Apr-12 3:17 
QuestionpageLoad() gives errors every time page changes at 'PageRequestManager' Pin
Dannoman12341-Feb-12 8:26
Dannoman12341-Feb-12 8:26 
GeneralGoogle Map Control Pin
mydream201925-Nov-11 1:40
mydream201925-Nov-11 1:40 
GeneralRe: Google Map Control Pin
User 99267428-Nov-11 16:19
User 99267428-Nov-11 16:19 
GeneralRe: Google Map Control Pin
mydream201930-Nov-11 1:17
mydream201930-Nov-11 1:17 
QuestionVery Good Article Pin
Anjum.Rizwi18-Jul-11 1:11
professionalAnjum.Rizwi18-Jul-11 1:11 
GeneralGet the Latitude,Longitude and the Zoomlevel when the AutomaticBoundaryAndZoom = true Pin
Maniaknl27-Oct-10 23:38
Maniaknl27-Oct-10 23:38 
QuestionAlternate Address Pin
Igor_web8-Sep-10 3:44
Igor_web8-Sep-10 3:44 
GeneralUpdate Session Pin
LeilaGoharian13-Aug-10 0:04
LeilaGoharian13-Aug-10 0:04 
GeneralRe: Update Session Pin
User 99267418-Aug-10 10:46
User 99267418-Aug-10 10:46 
GeneralPlease help me! I want to display multiple maps on one page and each map shows a device. Thanks much! Pin
philvaptech23-Jun-10 18:16
philvaptech23-Jun-10 18:16 
GeneralHelp Pin
Arlen Navasartian19-Apr-10 14:32
Arlen Navasartian19-Apr-10 14:32 
GeneralUrgent : How to use Client ID (Premier User of google map api) Pin
Bhavesh Mandaliya14-Dec-09 1:36
Bhavesh Mandaliya14-Dec-09 1:36 
GeneralDirections Pin
Geoff King10-Jul-09 10:34
Geoff King10-Jul-09 10:34 

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.