Flex, Java/JavaFX, Silverlight, AJAX & RIA Frameworks

RIA Developer's Journal

Subscribe to RIA Developer's Journal: eMailAlertsEmail Alerts newslettersWeekly Newsletters
Get RIA Developer's Journal: homepageHomepage mobileMobile rssRSS facebookFacebook twitterTwitter linkedinLinkedIn


RIA & Ajax Authors: Javier Paniza, Pat Romanski, RealWire News Distribution

Related Topics: RIA Developer's Journal, XML Magazine

RIA & Ajax: Article

Google Maps and ASP.NET

Building a custom server control

I am sure that most of you have heard about or have had a chance to use Google Maps. It's a great service and I was really impressed by the responsiveness of the application and the ease with which users could drag and zoom maps from a Web browser. It has in many ways heralded the arrival of AJAX (Asynchronous JavaScript and XML), which I am sure will revitalize Web development in the days to come.

What makes the service even better is the availability of the Google Maps API (Application Programming Interface) as a free Beta service. The API allows developers to embed Google Maps in their custom applications. It also allows them to overlay information on the map and customize the map to their needs. As I write this article there are quite a few sites that utilize Google Maps, and more and more of them are appearing by the day.

The API by itself is pretty straightforward and easy to use; however, it requires the developer to have a good command of JavaScript because it extensively relies on client-side Java scripting. In this article we will be looking at building a custom ASP.NET server control that would allow a .NET developer to harness the power of Google Maps in the code-behind model. We will see how to accomplish most of the functionality exposed by Google Maps using this control, and we'll also see how to data bind the control, thereby allowing developers to easily build data-driven custom ASP.NET Web applications. The control would eliminate the need for the developer to write any JavaScript to accomplish most of the Google Map functionality.

Some Google Maps Basics
Before we get into the details of the ASP.NET control, let's look at the basics of the Google Maps API. A detailed description of the API can be found at www.google.com/apis/maps/documentation/. The first step before using Google Maps is to register for a key with Google (www.google.com/apis/maps/signup.html). This is absolutely free and hardly takes a few minutes. Each Web site that uses Google Maps has to have its own key. Make sure that you go through Google's Terms of Use (www.google.com/apis/maps/terms.html) before you start using Google Maps in your application.

Google represents an instance of the map as a "GMap" object. It is rendered as a div tag on the page. Once you have the map, it is possible to add controls to the map. Some of the available controls are the GMapType control that helps to toggle between the different views, namely map view, satellite view, and finally, the hybrid view that is a combination of map and satellite views. The other controls that are usually seen on the map are the ones used to add scrolling and zooming capability to the map. At the time of writing of this article, there are three different controls available:

  • GLargeMapControl: A large control for scrolling and zooming
  • GSmallMapControl: Similar to the previous one, but eliminates the zoom scale bar
  • GSmallZoomControl: Includes only Zooming controls

Once the map has been set up, it is possible to overlay information on the map. The information can be in the form of points or lines, though points are the most common ones. In order to overlay a point on the Google Map, it's necessary to know its longitude and latitude. At this time, Google does not provide any geo-coding services that give the co-ordinates corresponding to an address, but there are a couple of free services available on the internet that do so. www.Geocoder.us is one of them and given a US address, it returns the longitude and latitude for the same. Once the longitude and latitude have been obtained, create an instance of a GPoint (which is Google's representation of a point on the map), then create a GMarker using this point and add the marker to the instance of the Google Map. In order to Center and Zoom on a point, the GMap Object exposes a method ZoomandCenter that takes the point and the level of zoom required as the parameter. Just like points, it is possible to overlay lines on the Map. Those of you who have used Google Maps for directions will be familiar with the lines used to depict the route. In order to add a line to the Google Map, we need to create an instance of a GPolyLine object and pass in an array of GPoints to plot it. It is also possible to assign color, width, and opacity to the line. Another useful feature in Google Maps is the ability to show a pop-up window when the user clicks on a Marker. Google Calls this pop-up window by the name "InfoWindow."

The Google Maps ASP.NET Control (GMAP Control)
The main aim of this control is to allow .NET developers to utilize the functionality of Google maps as a server-side control by writing little to almost no JavaScript at all. It is more of a .NET wrapper around the Google API; however, because it is a full-fledged ASP.NET server-side control, it is possible to bind data to the control, thereby increasing the usability of Google Maps. In the following sections we will see how to use this control to implement most of the common functionality of Google Maps. Before we do so, let's take a look at the control. The principal class of the control is the "GMapControl" class. This class in turn references the following classes (most of these classes are the .NET equivalents of the classes used by Google):

  • GPoint: This is the class representation of a geographical point and exposes latitude and longitude as its two properties.
  • GPoints: This class represents a collection of GPoint objects.
  • GIcon: Represents a custom icon that is used as an overlay on the map. The GIcon class exposes the following properties: the Image URL, which as the name suggests, is the URL of the image used to represent the icon; ShadowImageURL is the URL of the shadow associated with the icon; IconSize and ShadowSize represent the size of the icon and the shadow, and the last two properties are IconAnchor and InfoWindowAnchor, which specify the point where the icon should be anchored to the map relative to its top-left corner and the point where the Info window should be anchored to the map.
  • GLine: This is a line that the user wishes to overlay on the map. By default it takes a collection of points (GPoints) as an argument in its constructor. It is also possible to set the color of the line as well as its weight and opacity through an overloaded constructor.
  • GMarker: This is the .NET representation of the Google Maps class GMarker. The default constructor accepts an instance of a GPoint class. It also has an overloaded constructor that takes a GIcon along with the GPoint in case the developer wishes to use a custom icon to represent the marker.
  • GSize: Represents a two-dimensional size measurement.
  • JScriptGenerator: This is an internal class and has more of a helper function. It generates most of the JavaScript functions that are needed by the control.
  • HelperColorConvertor: This class is used to convert a color into its equivalent Hex value. This class is marked as internal.
  • HelperDataResolver: This is an internal class that helps in data binding and has just one method. The method casts a datasource object into an object that implements the IEnumerable interface. The help file that describes in detail the different methods and properties of the classes involved is available as a download.

Getting Started in ASP.NET
Before we use the ASP.NET control in our application, there are a few things that need to be taken care of to ensure that it works as desired.

Web.config File
The GMAP control renders itself as a DIV tag, however for non-Internet Explorer Browsers, ASP.NET renders the div tag as tables. If you want the page to render the GMAP control properly in other browsers such as Netscape and Firefox, include the browser cap section shown in Listing 1 into the Web.config file of your application.

Page Configuration
Google has certain recommendations for the HTML standards on pages that contain the map to make sure that the layout is predictable across different browsers. A detailed description of the same can be found in the Google maps documentation. It is imperative that you follow these standards, especially if you plan to overlay lines on your map. For lines to be rendered on the map, you need to include the VML namespace in the HTML page for Internet Explorer browsers. Make sure that you don't forget to do this, because otherwise the lines will not be displayed in Internet Explorer. The HTML tag of your page should at the minimum look like the snippet below:

<HTML xmlns:v="urn:schemas-microsoft-com:vml">

Adding to the Toolbar
This step is optional; however if you are using Visual Studio .NET as your IDE, I would recommend that you go ahead and add the GMap control to your toolbox. The advantage of doing so is that you can easily drag and drop the GMap control onto an ASPX page like any other ASP.NET control, and Visual Studio will automatically register the control on your page. Figure 1 shows the GMap control on the toolbar.

Creating a Basic Map Using the Control
Since we are done with the setup, let's go ahead and create a simple example using the control. We will add the GMap control to the page, set its dimensions, and make it center and zoom at a particular point. For the sample application used in this article, I have saved the map key in the Web.config file and will be setting the GoogleMapKey property of the control from the config file. I will be setting the map type of the control to be that that of "Map." In case no map type is specified, the control defaults to the preset "Map." The GMap Control also supports satellite and hybrid map types. Make sure that you center and zoom at a point, otherwise all that will show up will be a grey area. Listing 2 shows the code for this example and Figure 2 shows the output.

Setting the GMap Control Properties
Let's go ahead and set some properties to the basic example we just created. The GMap control exposes a set of properties that allows the developer to customize the control to his or her needs. If we wish to give the user the flexibility to change the view, we set the ShowMapTypeControl property of the control to true. By default, the user is able to drag the map, however, if we do not wish the user to drag the map around, we can set the EnableDragging property to false. To allow the user to be able to scroll or zoom, set the ScrollControlType property of the control. There are three different options: "large," "small," and "zoom only," to correspond to the controls offered by Google. Listing 3 shows the source code and Figure 3 shows the output in the browser.

More Stories By Jeevan Murkoth

Jeevan Murkoth is a Microsoft Certified Solutions Developer (MCSD) in .NET (Early Achiever) and a Microsoft Certified Application Developer (MCAD) in .NET. He currently consults for Tennessee Valley Authority and lives in Chattanooga, TN. He has an MS in Management Information Systems from Texas Tech University.

Comments (78) View Comments

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


Most Recent Comments
Siva Ramaswami 08/08/06 11:43:52 AM EDT

Hi Jeevan,
Awesome article. Do you have any sample code to automatically make an overlay marker popup in response to an event on the page, like clicking a button?
Thanks again for the great article and examples.
-Siva

Jeevan 08/01/06 01:00:47 PM EDT

Hi Siva,
Its there. Click on the link and then click on Additional code to get the source code and the dll
http://res.sys-con.com/story/jan06/171162/source.html

AJAXWorld News Desk 08/01/06 12:52:10 PM EDT

I am sure that most of you have heard about or have had a chance to use Google Maps. It's a great service and I was really impressed by the responsiveness of the application and the ease with which users could drag and zoom maps from a Web browser. It has in many ways heralded the arrival of AJAX (Asynchronous JavaScript and XML), which I am sure will revitalize Web development in the days to come.

Siva Ramaswami 08/01/06 12:34:35 PM EDT

Hi,
How do I go about downloading the actual control (MapControl.dll) itself?
I lookedd into the link provided here but could not find it.
Thanks
-Siva

AJAXWorld News Desk 08/01/06 11:54:57 AM EDT

I am sure that most of you have heard about or have had a chance to use Google Maps. It's a great service and I was really impressed by the responsiveness of the application and the ease with which users could drag and zoom maps from a Web browser. It has in many ways heralded the arrival of AJAX (Asynchronous JavaScript and XML), which I am sure will revitalize Web development in the days to come.

Jeevan 08/01/06 11:06:37 AM EDT

Hi John ,
Try this
GMapControl1.Height= new Unit(400)
GMapControl1.Width= new Unit(400)
This should work

Jeevan

John 07/31/06 12:14:55 PM EDT

I am having trouble in converting this to VB.NET. I can not set the map height or width to an integer. The error I get concerns the lines "GMapControl1.Height = 400" or GMapControl1.Width = 400." I get the error "Value of type 'Integer' cannot be converted to System.Web.UI.WebControls.Unit"

I have tried creating properties for the width and height and using it that way but that does not work.

Any ideas?

Thanks

krishana 05/11/06 03:44:41 AM EDT

kklkslkd

Rick Gross 04/28/06 02:36:29 PM EDT

Never mind, was referencing the wrong version of the Control.
Thanks again for all the great work!
Rick

Rick Gross 04/28/06 02:25:42 PM EDT

Jeevan,
I'm working in c# and can't get the following to work:
GMapControl1.DataSource=dt;
GMapControl1.MarkerLatitudeField="latitude";
GMapControl1.MarkerLongitudeField="longitude";
GMapControl1.MarkerText="htmltext";
There is no definition in the control. Any ideas? And thanks for you work on this!
Thanks,
Rick

Jacob Reimers 04/21/06 07:48:17 AM EDT

I was surprised when I looked at the date for this article. At this point it should have been known that the Google API was being changed to version 2. Version 1 will be obsolete shortly.

I have a map control that uses version 2 of the API at http://www.reimers.dk

SYS-CON Australia News Desk 04/05/06 01:51:09 PM EDT

I am sure that most of you have heard about or have had a chance to use Google Maps. It's a great service and I was really impressed by the responsiveness of the application and the ease with which users could drag and zoom maps from a Web browser. It has in many ways heralded the arrival of AJAX (Asynchronous JavaScript and XML), which I am sure will revitalize Web development in the days to come.

Jeffrey 03/10/06 08:22:27 AM EST

Jeevan,
Thanks for the reply. I cannot find your email can you send me an email to [email protected]? Thanks a million!!!!!

Jeffrey

Jeevan 03/10/06 12:16:37 AM EST

Hi Jeffrey,
Its the same control that works both in VB.NET and C# .Drop me an email and I'll send u the VB.NET code with databinding working

Jeffrey 03/09/06 08:39:52 PM EST

Jeevan,
Great article and great control. I have done some massaging and got the control to work in VB.Net. However I cannot get the GmapControl1.Datasource to be reconized. The GmapCOntrol1.Databind shows up in itellisense but not GmapControl1.Datasource.
Dim ds As DataSet = oGetSites.GetSitesByDistance(ConceptID, Session("BaseState"), 100)

GMapControl1.DataSource = ds
I get an error saying the Datasource was not reconized. Can you send me the VB.net control you mentioned?

Again Thanks

Jeevan 03/02/06 09:42:15 AM EST

Hi Lee,
Please find below the link to download the control, the source code and the help file
http://res.sys-con.com/story/jan06/171162/source.html

Jeevan 03/02/06 09:37:56 AM EST

Hi Jim,
I tried out your code and got it to work. The only thing I did was uncomment the lines where you set the width and height for the control . I have the VB.NEt web project. If your are interested drop me an email at jeevancm at gmail .com and I can send it out to you

Lee Butler 02/28/06 06:57:21 PM EST

Jeevan,

Great article. Thank you for the good read. I would love to put the control to use in some online mapping tools I'm playing with. Will your control be available for download anytime soon?

Thanks again Jeevan.

- Lee Butler

NHJim 02/21/06 07:15:36 PM EST

Jeevan,

Thanks for offering to take a look at this code. What I did was take the existing code from your example in C++ and moved it to VB.

First went into an existing working project.
Added a new Map2.aspx
Added the GMapControl to my toolbar Web Forms
Added the new control to the Web Page
Renamed the control ID to GMapControl1

Pasted in all of your code from the C++ demo into the page load of this Web page
Added the list of imports
and started messing with the controls
some I could get set some I just remed out

The page will load without error in View in Browser - but I can not get it working.
I have a older Google Map from last year that shows an event map and then has 8 push pins of a parking lot that the people can park in.
This year looking at the google map the pins are all in place but the map detail is no longer loading.

I would love to get this working - it is for a not for profit event rotaryribfest.org all the money made is give away to local and 3ed world charties...

Now for my code:

Imports System
Imports System.Collections
Imports System.ComponentModel
Imports System.Data
Imports System.Drawing
Imports System.Web
Imports System.Web.SessionState
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.HtmlControls
Imports MapControl
Imports System.Configuration

Public Class Map2
Inherits System.Web.UI.Page

Protected WithEvents GMapControl As MapControl.GMapControl

'Namespace GMapWebTest

#Region " Web Form Designer Generated Code "

'This call is required by the Web Form Designer.
Private Sub InitializeComponent()

End Sub
Protected WithEvents GMapControl1 As MapControl.GMapControl
Protected WithEvents Label1 As System.Web.UI.WebControls.Label

'NOTE: The following placeholder declaration is required by the Web Form Designer.
'Do not delete or move it.
Private designerPlaceholderDeclaration As System.Object

Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
'CODEGEN: This method call is required by the Web Form Designer
'Do not modify it using the code editor.
InitializeComponent()
End Sub

#End Region

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'Put user code to initialize the page here
' Dim strNumber As String = 400
' GMapControl1.Width = 400
'GMapControl1.Height = 400
GMapControl1.MapType = MapControl.GMapType.MAP

' GMapControl1.GoogleMapKey=ConfigurationSettings.AppSettings["DevKey"]
GMapControl1.GoogleMapKey = "THIS IS MY WORKING KEY - BUT I REMOVED IT "
GMapControl1.CenterAndZoom(New GPoint(36.224264, -86.628273), 9)

InitializeComponent()
' base.OnInit(e)
' this.Load += new System.EventHandler(this.Page_Load);

End Sub

End Class

Thanks again

Jim

Jeevan 02/19/06 01:44:24 AM EST

Hi Jim,
The control works in VB.NET & C# like any other .NET control .I would need to see your code to trouble shoot

NHJim 02/15/06 03:46:52 PM EST

THANK YOU!
For the past year I drop a day a month on trying to get this working for a few not for profits. This is the best in 60+ hours of research that I have found. IT WORKS!

Now that I have crossed over from the dark side of Access to VB.Net and ASP.Net I wonder - yes a stupid question - if there is a way I can get this to work in VB.Net. When I added the MapControl.dll into the bin of your MapTest.sln I could get the GMapControl added and working in C#.

I did the same thing in a VB.Net solution and I can not set any values in the Page_Load to the GMapControl1. Am I doing something wrong?

I changed all usings to Imports
I have the protected working (no error)
I can not get namespace to work
I can not get base.OnInit(e) to work
I can not get tje this.Load line to work

Overall I would love to be able to run this in VB.Net so if I am doing something stupid that is a simple fix I would love to know about it. If the MapControl.dll is only for C# then would you please let me know as well.

THANKS - THIS IS THE BEST DOCUMENT I HAVE FOUND!

Niko 01/25/06 12:31:05 PM EST

Hi Jeevan,

enjoyed your article. Hope to put it to use pretty soon...

Jeevan 01/23/06 12:39:51 PM EST

Hi Bill,
The link to the code
http://res.sys-con.com/story/jan06/171162/source.html

(The Real) Bill Pierce 01/23/06 11:42:10 AM EST

Hi Jeevan,
I'm not sure who posted the comment from 23 Jan 2006 (It wasn't me).

I recently found a link to your article and I must say there are some startling similarities. I would like to download your code and checkout your approach. I am new to the .Net Developer's Journal website. I can't find a link to download your code or view any of your code listings. Can you email me a copy?

Thanks,
-Bill

Jeevan 01/23/06 10:05:43 AM EST

Hi Bill,
Took a look at your control. your approach and mine are totally different.Why don't you download the code and take a look. Case of same result but totally different approaches.As for the flow of the article.. I have just followed the step by step approach similar to the one in Google documentation for which I have given due credit.

Bill Pierce 01/23/06 02:49:48 AM EST

This author has just rehashed my article that I wrote for CodeProject:

http://www.codeproject.com/aspnet/LatLaysFlat-Part1.asp
http://www.codeproject.com/aspnet/LatLaysFlat-Part2.asp
http://www.codeproject.com/aspnet/LatLaysFlat-Part3.asp
http://www.codeproject.com/aspnet/LatLaysFlat-Part4.asp

What a jerk!

Greg 01/19/06 10:28:17 PM EST

Cool article..Very useful control

SYS-CON Belgium News Desk 01/16/06 12:41:39 PM EST

I am sure that most of you have heard about or have had a chance to use Google Maps. It's a great service and I was really impressed by the responsiveness of the application and the ease with which users could drag and zoom maps from a Web browser. It has in many ways heralded the arrival of AJAX (Asynchronous JavaScript and XML), which I am sure will revitalize Web development in the days to come.