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

Stats

726.1K 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

 
GeneralMy vote of 5 Pin
Rodrigo Ratan [R2]1-Nov-21 9:27
Rodrigo Ratan [R2]1-Nov-21 9:27 
QuestionShowing multiple routings Pin
Member 450973722-Jul-20 11:13
Member 450973722-Jul-20 11:13 
QuestionUsing animation when polylines get created Pin
Siddharth_Gupta3-Jul-18 4:19
Siddharth_Gupta3-Jul-18 4:19 
Questionhow do i display a data from sql with lat , lan in alert box , when use click on map Pin
Member 121190756-Jan-16 1:18
Member 121190756-Jan-16 1:18 
BugFacing error on GoogleObject error Pin
Member 121190756-Nov-15 2:09
Member 121190756-Nov-15 2:09 
Questionhow can i calculate length of polyline Pin
deepakmishra_mrt4-Jun-15 2:30
deepakmishra_mrt4-Jun-15 2:30 
QuestionUnrivaled For Ease Of Use In ASP.NET Pin
Cleveland Mark Blakemore15-Feb-15 18:30
Cleveland Mark Blakemore15-Feb-15 18:30 
Questionmap click not work inside mozilla ! Pin
meysamg26-Dec-14 0:51
meysamg26-Dec-14 0:51 
Questionmouse hover for infohtml in Google Maps Control Pin
Member 1056580311-Nov-14 9:01
Member 1056580311-Nov-14 9:01 
QuestionHow to get a location (long, lat) where click on maps Pin
do dinh vinh27-Jul-14 18:21
do dinh vinh27-Jul-14 18:21 
Questionnot run framework 4.0 Pin
nct197220-Jul-14 22:21
nct197220-Jul-14 22:21 
GeneralMy vote of 5 Pin
rj475613-Mar-14 16:56
rj475613-Mar-14 16:56 
Question[My vote of 2] No solution file Pin
TheeStudent24-Oct-13 3:40
TheeStudent24-Oct-13 3:40 
AnswerRe: [My vote of 2] No solution file Pin
rj475613-Mar-14 16:59
rj475613-Mar-14 16:59 
Questionhow to display label pushpin Pin
nct197221-Aug-13 5:47
nct197221-Aug-13 5:47 
QuestionI want to change design of InfoHTML Pin
Dhaval Ptl19-Aug-13 8:58
Dhaval Ptl19-Aug-13 8:58 
QuestionError:the base class includes the field 'GoogleMapForASPNet1',but its type(GoogleMapForASPNet) is not compatible with the type of contol(ASP.googlemapforaspnet_ascx) Pin
j.basterra17-Apr-13 4:34
j.basterra17-Apr-13 4:34 
QuestionQuestion. Pin
Member 836192910-Apr-13 21:20
Member 836192910-Apr-13 21:20 
QuestionAdd Ajax frame work to my web application in order to use google map Pin
rongqu23-Jan-13 5:09
rongqu23-Jan-13 5:09 
QuestionPass the code to Google apis v3 Pin
tgolfieri28-Sep-12 8:52
tgolfieri28-Sep-12 8:52 
AnswerRe: Pass the code to Google apis v3 Pin
DotNetCoderJunior25-Mar-13 3:55
DotNetCoderJunior25-Mar-13 3:55 
AnswerRe: Pass the code to Google apis v3 Pin
Tim_Mackey20-Oct-13 23:58
Tim_Mackey20-Oct-13 23:58 
QuestionVisual Studio2008 restarts on opening GoogleMapForASPNet.ascx file Pin
Shiridish25-Sep-12 21:46
Shiridish25-Sep-12 21:46 
QuestionOn click event in IIS is not working Pin
SREEKAN218-Sep-12 7:06
SREEKAN218-Sep-12 7:06 
AnswerRe: On click event in IIS is not working Pin
nct197220-Jul-14 22:59
nct197220-Jul-14 22:59 

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.