Click here to Skip to main content
16,016,227 members
Articles / Web Development / ASP.NET

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 799.6K   16.6K   284   186
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)



Comments and Discussions

 
GeneralCannot remove points from the map Pin
dosdemon7-Oct-08 0:37
dosdemon7-Oct-08 0:37 
GeneralRe: Cannot remove points from the map Pin
tronix0115-Dec-08 3:03
tronix0115-Dec-08 3:03 
GeneralGreat work Pin
san2112011-Sep-08 22:40
san2112011-Sep-08 22:40 
QuestionWhere do i use API key ? Pin
itsmeyes27-Aug-08 22:01
itsmeyes27-Aug-08 22:01 
QuestionAdd textbox and buttons to pushpins ? Pin
itsmeyes27-Aug-08 21:53
itsmeyes27-Aug-08 21:53 
QuestionRuntime Error in Internet Explorer 7: right click on the map Pin
sergei82fn18-Aug-08 21:03
sergei82fn18-Aug-08 21:03 
QuestionThe Type or namespace 'GoogleObject' can't be found - my environment is vs 2008 Pin
YingHsuan31-Jul-08 12:33
YingHsuan31-Jul-08 12:33 
AnswerRe: The Type or namespace 'GoogleObject' can't be found - my environment is vs 2008 Pin
YingHsuan31-Jul-08 20:00
YingHsuan31-Jul-08 20:00 
Dear Author
Thanks for your attention of this problem.
I solved this problem by searching on google continuing/
this problem will happened when the web site is a project type, not a website.

Thanks.
Joy
GeneralRe: The Type or namespace 'GoogleObject' can't be found - my environment is vs 2008 Pin
sajidhaq17-Mar-12 12:28
sajidhaq17-Mar-12 12:28 
QuestionCallback Pin
oleop29-Jul-08 11:24
oleop29-Jul-08 11:24 
Questionusing my custom maps Pin
Thuan_pham23-Jul-08 5:57
Thuan_pham23-Jul-08 5:57 
Generaltabinfowindow Pin
lras120218-Jul-08 5:36
lras120218-Jul-08 5:36 
GeneralRe: tabinfowindow Pin
YoungJoe1-May-09 0:23
YoungJoe1-May-09 0:23 
GeneralGreat article,but i have a problem Pin
yakida11-Jul-08 0:46
yakida11-Jul-08 0:46 
GeneralExcellent! Pin
Jacob Dixon29-Jun-08 5:37
Jacob Dixon29-Jun-08 5:37 
GeneralRe: Excellent! Pin
Jacob Dixon29-Jun-08 6:41
Jacob Dixon29-Jun-08 6:41 
NewsGoogle Maps User Control documentation Pin
User 9926744-Jun-08 8:48
User 9926744-Jun-08 8:48 
QuestionTwo controls on one page? Pin
jaymo1731-May-08 10:17
jaymo1731-May-08 10:17 
AnswerRe: Two controls on one page? Pin
Member 264714020-Oct-09 21:53
Member 264714020-Oct-09 21:53 
QuestionCannot center from within AJAX Toolkit's TabContainer Pin
david.templeton28-May-08 12:06
david.templeton28-May-08 12:06 
GeneralRe: Cannot center from within AJAX Toolkit's TabContainer Pin
User 99267429-May-08 4:01
User 99267429-May-08 4:01 
Questionany suggestions for optimisation? Pin
Tim_Mackey27-May-08 3:26
Tim_Mackey27-May-08 3:26 
AnswerRe: any suggestions for optimisation? Pin
User 99267429-May-08 3:58
User 99267429-May-08 3:58 
GeneralRe: any suggestions for optimisation? Pin
Tim_Mackey4-Jun-08 2:01
Tim_Mackey4-Jun-08 2:01 
GeneralRe: any suggestions for optimisation? Pin
Bhavan Nerella6-Oct-09 6:55
Bhavan Nerella6-Oct-09 6:55 

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.