Working with GoogleMap Control in ASP.NET

This article will show you how to implement the GoogleMap control in your ASP.NET website, as well as how to point the map to an address entered by user, add and remove markers and get the position where the user clicked on the map using the combination of Javascript and codebehind.

Introduction

This article will show you how to implement the open source Google Map control for .NET hosted at http://googlemap.codeplex.com/
The final result of the step-by-step guide on implementing the control can be seen on the image below:

Looks nice and simple. What this application will allow you to do is to search
for any city or address (addresses are best tested with some US addresses like "25th Avenue New York") and zoom in on the location and placing a marker on the given location. Let's move on.

Downloading and adding the GoogleMap control to your project

First things first, we need to download the control from
Codeplex and reference it either inside our page or globally inside the web.config file. To download the control go to http://googlemap.codeplex.com/ and click the Download button on the right of the page. You will be redirected to a new page where you will be asked whether or not you agree to the terms of the licence. Click I Agree and download will begin. It's a small file so it should be finished quickly. Once the download is complete open up the folder where you saved the file and unpack the control by using Winrar or some other similiar unpacking tool. Open up the unpacked folder and you will be presented with 2 files: Artem.GoogleMap.pdb and Artem.GoogleMap.dll.

Create a new
web application in your Visual Studio and add a new folder named Bin. Now right click the newly created folder and select "Open folder in Windows Explorer". This will open the newly created folder. Copy the above mentioned files to this folder and close Windows Explorer.

Now, there are 2 ways to reference the control inside your project. 1st is t
o globally register the control in every page of the project by using the web.config file and 2nd is to register the control under Page declaration only on the Page where you will use the control. Since this application consists of only 1 page I will use the 2nd approach. This is what the Register control declaration looks like on the page:

<%@ Register Assembly="Artem.GoogleMap" Namespace="Artem.Web.UI.Controls" TagPrefix="cc1" %>

Of course, you can change the TagPrefix if you want but there's no need
to. The 2nd step to be able to test the map locally is to Sign Up for the Google Maps API Key. This can be done really easily by visiting the following URL:

http://code.google.com/apis/maps/signup.html

Note however that this requires you to have a Google account to register. When asked to enter your website's URL just enter localhost so
at the end it looks like http://localhost

When you've done this you will
be sent to another page and you will see your Google Maps API Key on the top of the page. Save it somewhere so you have it for future reference.

Page markup and Javascript

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<%@ Register Assembly="Artem.GoogleMap" Namespace="Artem.Web.UI.Controls" TagPrefix="cc1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Google Map Tutorial</title>
<link href="css/default.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
function getLatLongValues(overlay, point) {
if (point) {
document.getElementById("latValue").value = point.lat();
document.getElementById("lngValue").
value = point.lng();
document.forms[0].submit();
}
}

function setFocus(controlName) {
document.getElementById(controlName).focus();
}

</script>
</head>
<body onload="setFocus('txtCity');">
<form id="form1" runat="server">
<div class="pagewrapper">
<div id="header">
City name or address:
<asp:TextBox ID="txtCity" runat="server"></asp:TextBox>
<asp:Button ID="btnSearch" runat="server" Text="Go" onclick="btnSearch_Click" />
</div>
<cc1:GoogleMap ID="mapControl" runat="server" OnClientClick="getLatLongValues" Width="100%" Height="740px" Zoom="3" Latitude="10" Longitude="10" Key="PUT YOUR MAPS API KEY HERE">
</cc1:GoogleMap>
</div>

<asp:HiddenField ID="latValue" runat="server" />
<asp:HiddenField ID="lngValue" runat="server" />
</form>
</body>
</html>

As you can see the markup is rather
simple. We have a header div which hosts the txtCity TextBox and a btnSearch button and underneath that we got the GoogleMap control itself. The important to note on the map is the OnClientClick event. This is what we will use to read where the user clicked on the map by using Javascript and then submitting these values to codebehind. As you can see we also have 2 asp:HiddenField controls which I will use to read the clicked location. As you can see we have 2 Javascript functions in the page, 1 is purely cosmetical (setFocus) and I'm only using it to set the focus to a particular control whenever I need that (in this case setting the focus on txtCity control on onload event of the body) and the other is there to capture the map clicked event and store the location of the mouse click and submit the form afterwards.

Codebehind and Javascript explained

Now what happens with the code so far?
When the page is loaded the focus is set on the txtCity control. You enter the name of the ctiy but the Go button does nothing. Let's add the btnSearch_Click event. This is what it looks like:

protected void btnSearch_Click(object sender, EventArgs e)
{
// First clear old markers since this is a new search
mapControl.Markers.
Clear();

if (txtCity.Text != "")
{
mapControl.Address = txtCity.Text;
mapControl.Zoom = 15;

// add a new search marker
GoogleMarker marker =
new GoogleMarker(mapControl.Address);
marker.Title = mapControl.Address;
marker.Clickable =
false;
mapControl.Markers.
Add(marker);
}
}


As you can see the moment you click the Go button first we clear the map of all the currently present markers
and then check if the text inside the txtCity control isn't empty. We assign the Address property of the mapControl GoogleMap control and we also set the zoom level of the control. Further down we instantiate a new GoogleMarker (requires you to reference Artem.Web.UI.Controls on the page), set it's location to the current address of the mapControl, we set it's title and Clickable status (I've set mine to false because I don't want to display anything when you click the marker). At last we call the mapControl.Markers.Add(marker) method which adds this marker to the control's marker collection and therefore displays it on the map as well. The other overload for marker instantiation allows you to pass the lat and long values instead of address to position the marker which we will see in the next example. Ok we got the search part working. Let's move on to the map clicking part which is handled by Javascript.

If you take a look at the Google
Map control in our Page markup code you will see that we've set the OnClientClick property to a getLatLongValues Javascript function:

<cc1:GoogleMap ID="mapControl" runat="server"
OnClientClick="getLatLongValues" Width="100%" Height="740px" Zoom="3" Latitude="10" Longitude="10" Key="PUT YOUR MAPS API KEY HERE">
</cc1:GoogleMap>

Now let's
see what this function does:

function getLatLongValues(overlay, point) {
if (point) {
document.getElementById("latValue").value = point.lat();
document.getElementById("lngValue").value = point.lng();
document.forms[0].submit();
}
}

As
you can see the function takes in 2 parameters, the overlay parameter and the point parameter. The point parameter is the one we're interested in. It hold the lat and long values in it. So we first check if point is different than undefined and if it is we take the values of both point.lat() and point.lng() and store them in the 2 asp hidden fields on the bottom of the page. Afterwards we submit the form which causes Postback to occur. Now let's switch to the codebehind to see what goes on there:

protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
CheckForClickLocation();
}
}

As you can see on Page_Load I'm checking if the Page is posted back and if it is I'm calling the CheckForClickLocati
on() method in my page. Let's see how that looks like:

private void CheckForClickLocation()
{
// clear the marker
mapControl.Markers.
Clear();

// add new marker only if both hidden fields have a value
if (latValue.Value != "" && lngValue.Value != "")
{
GoogleMarker marker =
new GoogleMarker(Convert.ToDouble(latValue.Value), Convert.ToDouble(lngValue.Value));
marker.Clickable =
false;
mapControl.Markers.
Add(marker);

mapControl.Latitude = marker.Latitude;
mapControl.Longitude = marker.Longitude;
mapControl.Zoom = 13;
}
}

As you can see here we're first clearl
ing the current markers on the map and then we're checking if latValue and lngValue hidden fields have any value in them (remember postback can occur by a button we have on the page as well in which case there was no actual map click). In case we have values in these 2 hidden fields we instantiate a new GoogleMarker object passing the values of the latValue and lngValue hidden fields converted into a double which is what the marker requires. We disable the clickable property because we don't need it and add the marker to the mapControl's Markers collection. After this is done we change the current Latitude and Longitude of the mapControl to the newly clicked location (note that I'm using marker.Latitude and marker.Longitude which also saves me from converting the values to double again), we set the zoom level to 13 and now the mapControl is centered on the newly clicked location where the marker is displayed as well.

Now if some of you wonder what happens if a postback by a button occu
rs and there are values in hidden fields as well? Well in case you're familiar with Page lifecycle you will know that this won't present any problem because what happens is that when a button is clicked and a postback occurs the Page_Load event fires before (this is important) the button click event and even though the markers were added in a Page_Load event they were deleted afterwards by the button click event.

Source Code and Conclusion

As you have seen in this article, usi
ng GoogleMap control in your ASP.NET website or application isn't hard at all. I hope you enjoyed reading this guide and if you got any comments or questions feel free to ask them and I will try to answer you as best as I can. Download the source code used in this guide below:

http://nullskull.com/FileUpload/-1672755420_GoogleMapTutorial.zip

Happy coding!

Sasha Kotlo.

By Sasha Kotlo   Popularity  (4432 Views)
Picture
Biography - Sasha Kotlo
- C#.NET Developement - SQL Server Database Applications - N-Tier Architecture Developement - Object Oriented Programming - XHTML/CSS - Javascript, jQuery - Photoshop, Illustrator, After Effects
My Website