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

Google Maps Control for ASP.NET - Part 1

By , 12 May 2008
 

Introduction

Most of us are familiar with the Google maps. Google has provided a very reach API to use in our own applications. But, we need some sort of JavaScript knowledge in order to use it. I don't know about others, but for me, it was a little difficult to use JavaScript along with the Google APIs in ASP.NET pages, specifically when using server-side functions to draw Google maps dynamically. For example, in my case, I wanted to pull latitude/longitude information from a SQL Server database and then use that to insert pushpins on a Google map. If you are familiar with the AJAX framework, you know the answer. You will have to call ASP.NET server-side functions from JavaScript and use the retrieved data to draw a Google map. How simple is that? :). Not at all; at least, not for me. So, I have decided to write a user control which can take care of the JavaScript part and allow me to concentrate on the server-side functions.

Features

  • Enables you to draw Google maps. No JavaScript knowledge required. Just drag and drop a control on your page.
  • Uses AJAX calls to retrieve server-side data.
  • Enables you to change pushpin positions on the fly. No need to refresh the full map.
  • Enables you to change pushpin icons on the fly.
  • Optimized to give you the best performance, i.e., only those pushpin data will be retrieved from the server that have changed.

How to use

In this part of the article, I don't want to explain how I created this control. Instead, I want you to start using it.

Requirements

  • Visual Studio 2005 or higher
  • Microsoft ASP.NET AJAX framework. You can download it from here.
  • Internet Explorer 7.0 or Mozilla Firefox 2.x. (Note: It may work on other browsers. I have tested on IE and Firefox only.)

Follow these steps in order to use it in your ASP.NET website:

  • Download the source from link provided on the top of this page. Extract it somewhere on your hard-drive.
  • Open the extracted folder as a website in Visual Studio, and run it. When you run this website, you will be able to navigate to a few sample pages.
  • To use this control in your application, copy the following files to your ASP.NET application in the same structure as shown below:

Now, we will add a reference to the AJAX library. If you are already using AJAX controls in your application, you can skip the following four steps.

Adding the AJAX Framework to your website

  • Right click on your website in Solution Explorer, and click Add Reference.
  • In the Add Reference window, select the System.Web and System.Web.Extensions libraries, and click OK. Note the library versions (in the picture, it is 1.0.61025.0; you may have another version, you can use any version).
  • Go to your web.config file, and add the following lines between the <System.Web></System.Web> elements.
  •     <httpHandlers>
          <remove path="*.asmx" verb="*"/>
          
          <add path="*.asmx" verb="*" 
          type="System.Web.Script.Services.ScriptHandlerFactory, 
          System.Web.Extensions,  Version=1.0.61025.0, 
          Culture=neutral, 
          PublicKeyToken=31BF3856AD364E35" 
          validate="false"/>
           
          <add path="*_AppService.axd" verb="*" 
          type="System.Web.Script.Services.ScriptHandlerFactory, 
          System.Web.Extensions, Version=1.0.61025.0, 
          Culture=neutral, 
          PublicKeyToken=31BF3856AD364E35" 
          validate="false"/>
          
          <add path="ScriptResource.axd" verb="GET,HEAD" 
          type="System.Web.Handlers.ScriptResourceHandler, 
          System.Web.Extensions, Version=1.0.61025.0, 
          Culture=neutral, 
          PublicKeyToken=31BF3856AD364E35" 
          validate="false"/>
          
        </httpHandlers>
        
        <httpModules>
          <add name="ScriptModule" 
          type="System.Web.Handlers.ScriptModule, 
          System.Web.Extensions, 
          Version=1.0.61025.0, Culture=neutral, 
          PublicKeyToken=31BF3856AD364E35"/>
        </httpModules>

    Note : Make sure that the version of the System.Web.Extension library is the same as what you have selected when you added the reference.

Adding the Google Maps control to your webpage

  • Open the page where you want to insert a Google map.
  • Drag the GoogleMapForASPNet.ascx control to your page.
  • You won't be able to see the Google Maps control in Design view. Instead, you should see a Script Manager as part of this control.

  • At this point, you can run your application, and you should be able to see a blank Google Maps control on your page, as shown below:
  • Let's add few pushpins on this map. For that, you will have to add some code in the Page_Load() event of your page.

Passing parameters to the Google Maps control

  • You must specify the Google Maps API Key for this component. You can obtain this key from Google.
  • if (!IsPostBack)
    {
     GoogleMapForASPNet1.GoogleMapObject.APIKey = "<YourGoogleMapKey>";

    Note that the initialization code for the map should go inside the if (!IsPostBack) block.

  • Optionally, you can specify which version of the Google Maps API to use. You can get more information about the Google Maps API version here.
  • GoogleMapForASPNet1.GoogleMapObject.APIVersion = "2";
  • Specify the width and height for the map. You can specify either in pixels, or in percentage relative to its container.
  •  GoogleMapForASPNet1.GoogleMapObject.Width = "800px";
     GoogleMapForASPNet1.GoogleMapObject.Height = "600px";
  • Specify the zoom level. The default is 3.
  •  GoogleMapForASPNet1.GoogleMapObject.ZoomLevel = 14;
  • Specify the Center Point for the map. The map will be centered on this point.
  •   GoogleMapForASPNet1.GoogleMapObject.CenterPoint 
        = new GooglePoint("CenterPoint", 43.66619, -79.44268);
  • Add pushpins for the map. This can be done by initializing the GooglePoint type object. In the constructor of GooglePoint, the first argument is the ID of this pushpin. It must be unique for each pin. The second and third arguments are the latitude and longitude.
  •   GoogleMapForASPNet1.GoogleMapObject.Points.Add(
            new GooglePoint("1", 43.65669, -79.45278));

    Alternatively, you can also do it like this:

    GooglePoint GP = new GooglePoint();
    GP.ID = "1";
    GP.Latitude = 43.65669;
    GP.Longitude = -79.43270;
    GoogleMapForASPNet1.GoogleMapObject.Points.Add(GP);

    You can add as many pushpins as you wish. Now, run the website again, and you should see pushpins on the map.

    Google-Maps-User-Control

Assigning custom icons to pushpins

  • You can assign your own icons with the Google Maps control. For that, first, copy your icons in some directory under the root directory of your website. You can assign an icon to a pushpin as shown below:
  • GP.IconImage = "icons/pushpin-blue.png";

    Note that the path to the image is relative to the root folder. You should have an icons (or whichever) directory in the root folder of your website.

  • You can add a description for a pushpin, which will pop up when the user clicks the pushpin.
  • GP.InfoHTML = "This is Pushpin-1";

  • You can format the InfoHTML property using standard HTML tags.
  • For example:

    GP.InfoHTML = "This is <font color='red'><b>Pushpin-1</b></font>";

    Up to this point, I have explained you the basics of using the Google Maps control. Now, let's implement some advanced functionality. Let's say, we want to move pushpins when the user does some action. For example, when a user clicks on a button. For that, follow the steps below.

Creating an interactive map

You can create an interactive map using the Google Maps control. You can move pushpins when the user clicks on a button. Here is how you can do it.

  • Insert a standard ASP.NET button on your web page. Write the following code in the Click event of this button:
  • protected void Button1_Click(object sender, EventArgs e)
    {
       GoogleMapForASPNet1.GoogleMapObject.Points["1"].Latitude += 0.003;
       GoogleMapForASPNet1.GoogleMapObject.Points["1"].Longitude += 0.003;
    }

    We are incrementing Latitude and Longitude values for the Pushpin 1 here. Note that I am using the ID (in the above code, "1") of the pushpin to set the new Latitude and Longitude.

  • Run your application and click on the button. You will note that the whole page gets refreshed (or postback). To stop it from posting back, you need to wrap this button with an AJAX UpdatePanel. Go to the Visual Studio toolbox and drag an AJAX UpdatePanel control on your page.
  • Move your button inside this UpdatePanel.
  • Now, run the website again and click on the button. You should notice that the page is not posting back now and the pushpin moves on the map.

Auto refreshing the map and GPS navigation

You can use the AJAX Framework's timer control in a similar way as the button control (as I have explained above). On the Timer_Tick() event, you can specify the new latitude longitude for all the pushpins. This way, the map will move all the pushpins automatically after a specified time delay. You can hook up any GPS service with this control to create a GPS navigation system.

Creating polylines with the Google Maps control

  • Create points for the polyline:
  • GooglePoint GP1 = new GooglePoint();
    GP1.ID = "GP1";
    GP1.Latitude = 43.65669;
    GP1.Longitude = -79.44268;
    GP1.InfoHTML = "This is point 1";
    GoogleMapForASPNet1.GoogleMapObject.Points.Add(GP1);
    
    GooglePoint GP2 = new GooglePoint();
    GP2.ID = "GP2";
    GP2.Latitude = 43.66619;
    GP2.Longitude = -79.44268;
    GP2.InfoHTML = "This is point 2";
    GoogleMapForASPNet1.GoogleMapObject.Points.Add(GP2);
    
    GooglePoint GP3 = new GooglePoint();
    GP3.ID = "GP3";
    GP3.Latitude = 43.67689;
    GP3.Longitude = -79.43270;
    GP3.InfoHTML = "This is point 3";
    GoogleMapForASPNet1.GoogleMapObject.Points.Add(GP3);
  • Create a polyline between points GP1, GP2, and GP3:
  • //Define polyline
    GooglePolyline PL1 = new GooglePolyline();
    PL1.ID = "PL1";
    //Give Hex code for line color
    PL1.ColorCode = "#0000FF";
    //Specify width for line
    PL1.Width = 5;
    
    //Add points
    PL1.Points.Add(GP1);
    PL1.Points.Add(GP2);
    PL1.Points.Add(GP3);
  • Add a polyline to the Google Maps control:
  • GoogleMapForASPNet1.GoogleMapObject.Polylines.Add(PL1);

Creating polygons with the Google Maps control

  • Create points for the polygon:
  • //Define Points for polygon
    GooglePoint GP1 = new GooglePoint();
    GP1.ID = "GP1";
    GP1.Latitude = 43.66675;
    GP1.Longitude = -79.4042;
    
    GooglePoint GP2 = new GooglePoint();
    GP2.ID = "GP2";
    GP2.Latitude = 43.67072;
    GP2.Longitude = -79.38677;
    .
    .//Define GP3,GP4,GP5,GP6 and GP7 in similar way
    .
    GooglePoint GP7 = new GooglePoint();
    GP7.ID = "GP7";
    GP7.Latitude = 43.66656;
    GP7.Longitude = -79.40445;
  • Create the polygon using the above points:
  • //Create Polygon using above points
    GooglePolygon PG1 = new GooglePolygon();
    PG1.ID = "PG1";
    //Give Hex code for line color
    PG1.FillColor = "#0000FF";
    PG1.FillOpacity = 0.4;
    //Stroke is outer border of polygon.
    PG1.StrokeColor = "#0000FF";
    PG1.StrokeOpacity = 1;
    PG1.StrokeWeight = 2;
    //Add points to polygon
    PG1.Points.Add(GP1);
    PG1.Points.Add(GP2);
    PG1.Points.Add(GP3);
    PG1.Points.Add(GP4);
    PG1.Points.Add(GP5);
    PG1.Points.Add(GP6);
    PG1.Points.Add(GP7);
  • Add the polygon to the Google Maps control:
  • GoogleMapForASPNet1.GoogleMapObject.Polygons.Add(PG1);

Go through the samples provided in the download. I have explained all sorts of circumstances in which you may want to use the Google Maps control. If you have any questions, feel free to ask.

In Part 2, I will explain to you the source code of the Google Maps user control and how to customize it for your own use.

History

Version 1.2

I am releasing a new version of this control. The following changes have been done in this version:

  • A minor bug related to polygons is fixed.
  • Now, you can enable or disable traffic overlays.

Version 1.1

The following features have been added in this version:

  • Now, you can draw polylines and polygons with this control.
  • A new property, GoogleMapObject.APIVersion, has been added to this control. This will allow users to use any version of the Google Maps API. The default version is 2.

License

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

About the Author

Shabdar Ghata
Web Developer
Canada Canada
Member
Software Developer
 
http://www.shabdar.org

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

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionError:the base class includes the field 'GoogleMapForASPNet1',but its type(GoogleMapForASPNet) is not compatible with the type of contol(ASP.googlemapforaspnet_ascx)memberj.basterra17 Apr '13 - 3:34 
I was using the earlier version of you code (for Google Api V2). Now i'm trying to upgrade my webapp to the new Google API. I downloaded the source code,copy the files needed on my application and dragged the GoogleMapForASPNET.ascx control to the page. I change all the name reference, but when I run the application
I get an error page saying:
 
Server Error in '/' Application,
Parase Error:the base class includes the field 'GoogleMapForASPNet1',but its type(GoogleMapForASPNet) is not compatible with the type of contol(ASP.googlemapforaspnet_ascx)
 
The extracted source code look like this:

    <form id="Form1" runat="server">
        <uc1:GoogleMapForASPNet ID="GoogleMapForASPNet1" runat="server" />
     </form>
</body>
 
Please can any one help me out, I really need your help.
QuestionQuestion.memberMember 836192910 Apr '13 - 20:20 
How to show the particular location?
Prabhu

QuestionAdd Ajax frame work to my web application in order to use google mapmemberrongqu23 Jan '13 - 4:09 
I am a new learner to use google map code and learning in Part1. I do not know how to add a reference for Ajax frame work. I did downloaded the toolkit as recommended, but still could not see the additional system.web.extension for the file I downloaded. I stopped on it. Could any one help me on it so that I can keep moving forward?
QuestionPass the code to Google apis v3membertgolfieri28 Sep '12 - 7:52 
Hi, Shabdar,
First of all thanks a lot - I've been using your open code very successfully for the last 3 years. As we all know next year the version 2 of google apis will not be available any more.
I tried to upgrade the java code for the version 3. It works (Smile | :) )!!) but I've got some trubbles with the map click event. Is there any possibility to get some help from you? Are you going to continue supporting your development with the control?
If you do I don´t have any problem to send the upgrated code to you.
Thank you very much!!!
Tatiana
AnswerRe: Pass the code to Google apis v3memberDotNetCoderJunior25 Mar '13 - 2:55 
Hi Tatiana
 
Have you managed to update to the latest maps, please can you show me how you did this.
 
Thanks Smile | :)
QuestionVisual Studio2008 restarts on opening GoogleMapForASPNet.ascx filememberShiridish25 Sep '12 - 20:46 
I have had no problems with all the files in this project but when I am trying to open the GoogleMapForASPNet.ascx file, Visual Studio 2008 restarts. It says it has encountered a problem and has to close. This happens only with this file and no other file causes this. I want to look into this file to get an idea of how it was implemented. Does it happen with anyone else too? Please let me the measures to overcome this.
QuestionOn click event in IIS is not workingmemberSREEKAN218 Sep '12 - 6:06 
HI, I am working with mapwithpolylines page, it is working fine when i am running is VS but when i hosted this on IIS it is not responding, ie it is not doing any thing, but after long time it is saying unresponsive, can you please help me out
GeneralIE9 does not show zoom controlmemberMember 878137130 Jul '12 - 8:36 
Hi! I used this control. When I tested it locally everything worked but after deployment to web server IE9 did not show zoom control on paqe.Also I got red crosses in places where tooltips should be shown. Any thoughts? Thank you in adnvance.
QuestionEncoded Polylinesmembercrayco66618 Jun '12 - 4:54 
Hi!
 
This version seems to be way too eavy and slow when it comes at dealing with polylines made up with thousands for points... Isn't there a way use Encoded Polylines instead? Any hint on how to acheive this will be greatly appreciated!!
crayco

QuestionI dont have App_Code folder in my applicationmembermrhammad113 May '12 - 14:51 
as i dont have app_code folder so i created new one with the name of that but still my code does work it gives me GoogleObject error?
QuestionAutomaticBoundaryAndZoom overridememberburn016126 Mar '12 - 15:52 
Slogged through and answered my own question below:
Set default ZoomLevel and CenterPoint on map. Once finished updating the points on the map, check if there are any displayed on the map
if(X.GoogleMapObject.Points.Count > 0) { 
X.GoogleMapObject.AutomaticBoundaryAndZoom = true; 
} else { 
X.GoogleMapObject.AutomaticBoundaryAndZoom = false; 
}
In App_Code/cGoogleMap.cs
GooglePoint _centerpoint = new GooglePoint();
    public GooglePoint CenterPoint
    {
        get { if (AutomaticBoundaryAndZoom) { return new GooglePoint(); } else { return _centerpoint; } }
        set { _centerpoint = value; }
    }
no idea why it works.
___________________________
 
Hi, I'm having abit of a problem with the AutomaticBoundaryAndZoom = true conflicting with ZoomLevel and CenterPoint.
 
What I want to happen: when AutomaticBoundaryAndZoom = true and there are points on the map then recenter and zoom. But if there aren't any points on the map, to use a default (manually defined) Zoom and CenterPoint (and AutomaticBoundaryAndZoom = false).
 
What is actually happening: If I set the Zoom and CenterPoint these seem to override AutomaticBoundaryAndZoom = true. Testing shows recenterandzoom is called, setZoom and setCenter are passed different values, but previously set Zoom and CenterPoint values are displayed instead.
 

How can i make AutomaticBoundaryAndZoom = true override the set Zoom level and CenterPoint so that the zoom level and centerpoint are used when there are no points on the map? (on post back)
QuestionInvisibility Bus Iconmembertinhnguyen8910 Mar '12 - 2:08 
Hi you,
I want to invisible bus station in google map by google map api. How can i do?
Thank u!
QuestionDo you handled the rightclick event ?memberMember 867892326 Feb '12 - 5:45 
Dear Sir,
Could you please add a quick menu with the right click event? , and add the featuers of adding a new center point or creat a new push pin in the selected new point ?
 
I can't recognize these features in the current version
 
thanks
tmg_2000@hotmail.com
QuestionGreat control but encountering JSErrors & only last pushpin showingmemberMember 455521625 Jan '12 - 2:10 
First off, let me say a very nice control indeed. Now, onto what I'm getting. I have put the GooglePoint inside a reader so I can try to set multiple points on the map. I'm only getting the last one. I think it has something to do with the errors I get. They are as follows:
 
1. I click ignore to get past this error:
Microsoft JScript runtime error: Unable to get value of the
Property 'PageRequestManager': object is null or undefined
 
2. When I click anywhere on the map, this event fires:
Microsoft JScript runtime error: '__doPostBack' is undefined
 
My code reads like this:
   protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            GoogleMapForASPNet1.GoogleMapObject.APIKey = ConfigurationManager.AppSettings["GoogleAPIKey"];
            GoogleMapForASPNet1.GoogleMapObject.Width = "600px"; // You can also specify percentage(e.g. 80%) here
            GoogleMapForASPNet1.GoogleMapObject.Height = "600px";
            GoogleMapForASPNet1.GoogleMapObject.ZoomLevel = 3;
            GoogleMapForASPNet1.GoogleMapObject.CenterPoint = new GooglePoint("1", 43.66619, -79.44268);
            string _csVHG = ConfigurationManager.AppSettings["SiteSqlServer"];
            SqlConnection conn = new SqlConnection(_csVHG);
            GooglePoint gp = new GooglePoint();
            try
            {
 
                string query = "Select PropertyID, Latitude, Longitude, ShortDescr, Description, PropertyImage from WEPropertyT";
                SqlCommand cmd = new SqlCommand(query, conn);
                conn.Open();
                SqlDataReader rd = cmd.ExecuteReader();
                int i = 0;
                while (rd.Read())
                {
                    gp.ID = i.ToString();
                    gp.Latitude = Convert.ToDouble(rd.GetValue(1));
                    gp.Longitude = Convert.ToDouble(rd.GetValue(2));
                    gp.InfoHTML = "Hello there!";
                    GoogleMapForASPNet1.GoogleMapObject.Points.Add(gp);
                    i++;
                }
                conn.Close();
            }
            catch (Exception ex)
            {
 
            }
        }
    }
 
As you can see, the code should work. However instead of getting 4 points (i have 4 records in my test) I get the very last one. Can someone shed some light on what is going on here?
QuestionGoogle Maps APIs in a non web-based applicationmemberAkhilesh K Gupta14 Dec '11 - 21:52 
Hi Shabdar,
 
Is it possible to use Google Maps APIs in a non web based app? so far what ever version I saw (Java script APIs or Google Maps control in your solution), its all to be used in a web based app!
 
Thanks,
- Akhilesh
AnswerRe: Google Maps APIs in a non web-based applicationmemberradioman.lt14 Dec '11 - 22:47 
check http://greatmaps.codeplex.com/
d{^__^}b - it's time to fly

GeneralRe: Google Maps APIs in a non web-based applicationmemberAkhilesh K Gupta14 Dec '11 - 23:20 
Thanks... looks like that is not with Google Maps APIs! I am looking for one with Google Maps API family only.
GeneralRe: Google Maps APIs in a non web-based applicationmemberradioman.lt15 Dec '11 - 0:31 
then use your browser ;}
d{^__^}b - it's time to fly

QuestionPushpin coding, google directions ?memberleutrimm14 Dec '11 - 10:33 
First thank you for the excellent example, I wanted to know if there is any way, to use those pushpins. Make a sidebar and put some links, so when I click one of them, to point the map where the pushpin is and open the text box description of the pushpin. If somebody could help me, I would really appreciate, because I need it that way for my project at college.
QuestionAbout directions by latitude and longitudememberDerek Tseng4 Nov '11 - 11:42 
Dear Sir
 
At beginning , I want to thank you for this good sample for us to learn from internet in taiwan.
but however, in the version 1.7, we lose the function of directions for using in latitude and longitude. Would you please tell us how to set up about this. If there is a simple sample file to show us, that would be great. And the students here also can learn about this more clearly and quickly. Really appriciate for this.
 
If there is any reply, please send to my email , derek8007@gmail.com. Thank you.
 

 
Best Reguards.,
 
from Derek Tseng in Taiwan
Questionvb.netmemberjf19723 Sep '11 - 2:37 
My code is written in vb - I get an error saying I can't use c and vb in same project - please advise
Questionusing Google Map Control in asp:Repeater - how to set parameters in OnItemDataBound Event?memberWilliam R. Miles8 Sep '11 - 11:19 
using Google Map Control in asp:Repeater - how can I set parameters in OnItemDataBound Event?
 
in the ItemDataBound Event Handler...
 
UserControl gmapFacility = e.Item.FindControl("gmapFacility") as UserControl;
 
gmapFacility. ??? (none of the parameters are exposed in Intelisense)
 
I was hoping to see...
gmapFacility.GoogleMapObject.APIKey
 
However, GoogleMapObject does not get exposed in the ItemDataBound Event Handler.
 
So how can I use the Google Map Control in an asp:Repeater?
GeneralMy vote of 5memberm.fotoohabadi@gmail.com21 Aug '11 - 22:00 
Thank you
QuestionIs it possible to get Google POI data and show them on the map ?memberJimz Rend21 Aug '11 - 21:26 
Is it possible to get Google POI data and show them on the map ?
Questionuse Google maps control in ProjectmemberMember 773041820 Aug '11 - 0:37 
hello
I need to know how I can use the control in a visual studio project
 
thanks

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.130523.1 | Last Updated 13 May 2008
Article Copyright 2008 by Shabdar Ghata
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid