Click here to Skip to main content
15,499,003 members
Articles / Web Development / ASP.NET
Article
Posted 18 Mar 2008

Stats

725.8K views
16.6K downloads
283 bookmarked

Google Maps User Control for ASP.NET

Rate me:
Please Sign up or sign in to vote.
4.90/5 (96 votes)
29 Oct 2021GPL37 min read
Google Maps control for ASP.NET
This user control allows users to add Google maps on ASP.NET web forms without writing complex JavaScript code.

Image 1

Introduction

Many of us are familiar with Google maps. Google has provided a very rich API that can be used in web applications via JavaScript. But this requires JavaScript knowledge. I don’t know about others, but for me, it was a little difficult to use JavaScript along with Google APIs in ASP.NET web application, specifically if I wanted to use server side functions to draw Google map dynamically. For example, in my case, I wanted to pull latitude longitude information from an SQL Server database and then use them to insert pushpins on Google map. So I decided to write Google maps user control for ASP.NET to take care of the JavaScript part.

Features

  • Ajax calls to retrieve server side data
  • Enables you to change pushpin positions on the fly. No need to refresh full page.
  • Enables you to change pushpin icons and positions from ASP.NET backend code
  • Pushpin click and drag event support in ASP.NET code
  • Map click event support in ASP.NET code
  • Directions support. Allows you to draw route between multiple points.
  • Polylines and Polygons support
  • Geocoding support, i.e., find latitude longitude from specific address and create pushpin on that location
  • Auto map boundary reset and zoom support to display all pushpins
  • Optimized to give you best performance, i.e., only those pushpin data will be retrieved from server that are 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 2019 Community Edition or higher
  • Internet Explorer or Firefox (Note: It may work on other browsers. I have tested on Internet Explorer and Firefox.)

Steps to Integrate with ASP.NET Application

  • Download or clone source from Github link provided above.
  • Open extracted folder as a website in Visual Studio and run it. When you run this website, you will be able to navigate few samples pages.
  • To use this control in your own ASP.NET application, copy the following sub folder to your application in root directory. Keep the same folder path as shown below. This is necessary. There are some relative paths used in user control and JavaScripts. “GoogleMapControl” sub folder contains necessary ascx and other files that are needed to render Google Map.

Copy Source Folder

Paste Source Folder

Once done, open your Solution in Visual Studio and go to Solution Explorer. Click on Show All files icon to show GoogleMapControl sub folder that we just copied in application root.

Visual Studio Solution Explorer Show All Files

Try building your solution after including GoogleMapControl sub folder. Ensure there are no errors.

Adding Google Map Control to Your Webpage

Drag “GoogleMapForASPNet.ascx” control to your web page(.aspx) file.

Add google map sub control to your web form (aspx) file.

At this point, you can run your application and you should be able to see a blank Google Map on your page as shown below. You will see an error as shown in the below screenshot. This error is because of missing API key for Google map.

Image 6

Follow the tutorial in the below link to get your own Google Maps API key. Please note that you need to have a project in Google cloud console with billing account to remove “For development purpose only” error. You can keep using development mode for testing with a blank API key.

Once you have your API key, go to Web.config file and add in the below section:

XML
<appSettings>
  <add key="GoogleAPIKey" value=""/>
</appSettings>

After adding Google API key, you should be able to see a normal Google map without any error.

Script Manager Error

In case you receive the below error, then this means you already have a Script Manager in either Master page or page where you are trying to add control.

Only one instance of a ScriptManager can be added to the page.

Only one instance of ScriptManager can be added to the page.

To resolve the above error, remove one instance of Script Manager from either GoogleMapControlForASPNet.ascx file or from your page.

To resolve this error, remove one instance of Script Manager from either GoogleMapControlForASPNet.ascx file or from your page.

How to Use this Control

Specify width and height for map. You can specify either in pixels or in percentage relative to its container.

C#
GoogleMapForASPNet1.GoogleMapObject.Width = "800px";
GoogleMapForASPNet1.GoogleMapObject.Height = "600px";

Specify zoom level. Default is 3.

C#
GoogleMapForASPNet1.GoogleMapObject.ZoomLevel = 14;

Specify Center Point for map. Map will be centered on this point.

C#
GoogleMapForASPNet1.GoogleMapObject.CenterPoint = 
   new GooglePoint("CenterPoint", 43.66619, -79.44268);

Add pushpins for map. This can be done by initializing GooglePoint type object. In constructor of GooglePoint, First argument is ID of this pushpin. It must be unique for each pin. Second and third arguments are latitude and longitude.

C#
GoogleMapForASPNet1.GoogleMapObject.Points.Add(new GooglePoint("1", 43.65669, -79.45278));

Alternatively, you can also do it like below:

C#
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 map.

Add pushpins

Assigning Custom Icon to Pushpins

You can assign your own icons with Google map control. For that, first copy your icons in some directory under root directory of your website. You can assign icon to a pushpin as below:

C#
GP.IconImage = "icons/pushpin-blue.png";

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

You can add description of a pushpin which will pop up when user clicks a pushpin.

C#
GP.InfoHTML = "This is Pushpin-1";

Marker Popup

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

C#
GP.InfoHTML = "This is Pushpin-1";

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

Creating Interactive Map

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

Insert standard ASP.NET button on your web page. Write the following code in click event of this button:

C#
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 value for Pushpin-1 here. Note that I am using ID (in the above code “1”) of pushpin to set new Latitude and Longitude.

Run your application and click on Button. You will note that whole page gets refreshed (or postback). To stop it from post back, you need to wrap this button with an Ajax Update panel. Go to Visual Studio toolbox and drag Ajax Updatepanel control on your page.

Add UpdatePanel

Move button inside update panel that we just placed.

Add UpdatePanel

Ty running the website again and click on Button. You should notice that now page is not posting back and Pushpin moves on map.

Auto Refreshing Map and GPS Navigation

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

Creating Polylines with Google Map Control

Create Polyline

Create points for polyline:

C#
//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 polyline between points GP1, GP2 and GP3:

C#
//Create Polygon using above points
GooglePolygon PG1 = new GooglePolygon();PG1.ID = "PG1";
//Give Hex code for line colorPG1.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 Polyline to Google Map control:

C#
GoogleMapForASPNet1.GoogleMapObject.Polygons.Add(PG1);

Traffic Overlays

To enable or disable traffic overlay, set the following property to true or false:

C#
GoogleMapForASPNet1.GoogleMapObject.ShowTraffic = true;

Note: Traffic overlays may not be available in every region. To get more information on traffic overlays, visit the below link:

https://developers.google.com/maps/documentation/javascript/trafficlayer

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

Version History

12th September, 2021

  • Compiled source with Visual Studio 2019 Community Edition
  • Checked into Github site for source control

Version 1.9.3 (24th January, 2017)

Following changes are made in this version:

  • Fixed missing API Key issue. Google Map do not seem to allow rendering map without API key anymore. Enter API Key in web.config file. Use the below section.
    <add key=”GoogleAPIKey” value=”Your API Key Here“/>

Version 1.9.2 (11th February, 2014)

Following changes are made in this version:

  • Fixed issue with Directions, map type, icon image and height. Change of direction line color is possible now.
  • Ability to change map type. Road map, satellite or hybrid is possible now. See example, MapWithSatelliteView.aspx.

License

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


Written By
Web Developer
Canada Canada
Software Developer

http://www.shabdar.org

Comments and Discussions

 
QuestionGeocoding available? Pin
shull15-Jan-09 19:30
Membershull15-Jan-09 19:30 
QuestionMultiple Pins/Markers at the same co-ordinates Pin
peteski15-Jan-09 6:10
Memberpeteski15-Jan-09 6:10 
GeneralThe aricle needs correction Pin
Saleh Orainy6-Jan-09 9:03
MemberSaleh Orainy6-Jan-09 9:03 
QuestionAdding code for pushpin click? Pin
eval993-Dec-08 6:27
Membereval993-Dec-08 6:27 
GeneralYou are really great. Pin
joinpramod5-Nov-08 17:44
Memberjoinpramod5-Nov-08 17:44 
QuestionShortest RoadWay Route between 2 points? [modified] Pin
Mayank Parmar5-Nov-08 1:57
professionalMayank Parmar5-Nov-08 1:57 
GeneralThe GoogleMapControl isn't working in Windows Mobile's browser Pin
Pankaj Chhura21-Oct-08 19:38
MemberPankaj Chhura21-Oct-08 19:38 
QuestionHow to "mark" a point Pin
dosdemon7-Oct-08 1:41
Memberdosdemon7-Oct-08 1:41 
Is there a way to put a number in each point that we plot on the map? Like for example when you do a search on http://maps.google.com/[^] for lets say "dunkin donuts" it will mark all results with a unique code (A, B, C ....). How can I do the same thing using your control?

Also, another question. Is it possible to change the background color of this marker from red to anything else?

Appreciate your help.
GeneralCannot remove points from the map Pin
dosdemon7-Oct-08 1:37
Memberdosdemon7-Oct-08 1:37 
GeneralRe: Cannot remove points from the map Pin
tronix0115-Dec-08 4:03
Membertronix0115-Dec-08 4:03 
GeneralGreat work Pin
san2112011-Sep-08 23:40
Membersan2112011-Sep-08 23:40 
QuestionWhere do i use API key ? Pin
itsmeyes27-Aug-08 23:01
Memberitsmeyes27-Aug-08 23:01 
QuestionAdd textbox and buttons to pushpins ? Pin
itsmeyes27-Aug-08 22:53
Memberitsmeyes27-Aug-08 22:53 
QuestionRuntime Error in Internet Explorer 7: right click on the map Pin
sergei82fn18-Aug-08 22:03
Membersergei82fn18-Aug-08 22:03 
QuestionThe Type or namespace 'GoogleObject' can't be found - my environment is vs 2008 Pin
YingHsuan31-Jul-08 13:33
MemberYingHsuan31-Jul-08 13:33 
AnswerRe: The Type or namespace 'GoogleObject' can't be found - my environment is vs 2008 Pin
YingHsuan31-Jul-08 21:00
MemberYingHsuan31-Jul-08 21:00 
GeneralRe: The Type or namespace 'GoogleObject' can't be found - my environment is vs 2008 Pin
sajidhaq17-Mar-12 13:28
Membersajidhaq17-Mar-12 13:28 
QuestionCallback Pin
oleop29-Jul-08 12:24
Memberoleop29-Jul-08 12:24 
Questionusing my custom maps Pin
Thuan_pham23-Jul-08 6:57
MemberThuan_pham23-Jul-08 6:57 
Generaltabinfowindow Pin
lras120218-Jul-08 6:36
Memberlras120218-Jul-08 6:36 
GeneralRe: tabinfowindow Pin
YoungJoe1-May-09 1:23
MemberYoungJoe1-May-09 1:23 
GeneralGreat article,but i have a problem Pin
yakida11-Jul-08 1:46
Memberyakida11-Jul-08 1:46 
GeneralExcellent! Pin
Jacob Dixon29-Jun-08 6:37
MemberJacob Dixon29-Jun-08 6:37 
GeneralRe: Excellent! Pin
Jacob Dixon29-Jun-08 7:41
MemberJacob Dixon29-Jun-08 7:41 
NewsGoogle Maps User Control documentation Pin
Shabdar Ghata4-Jun-08 9:48
MemberShabdar Ghata4-Jun-08 9:48 

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.