YOUR FEEDBACK
Ubuntu Here We Come! - Java Finally To Become 100% Open Source
Reader wrote: Since November 206, wow! that is a long process.

SYS-CON.TV
TOP MICROSOFT .NET LINKS


Google Maps and ASP.NET
Building a custom server control

Digg This!

Page 1 of 2   next page »

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.


Page 1 of 2   next page »

About 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.

Sajid Mushtaq wrote: i cant find a link to download the source code and the control. Please help. Regards, Sajid
read & respond »
Shabdar wrote: I have created similar control. It works with latest versions of Google Maps API. Here is the link, http://www.shabdar.org/go ogle-maps-user-control-fo r-ASP-Net-part1.html
read & respond »
Ghata wrote: This one works with GMAP2 http://www.shabdar.org/go ogle-maps-user-control-fo r-ASP-Net-part1.html
read & respond »
Balvinder wrote: I have downloaded GMap control and sample applications. But OverlayMarker and OverlayLine does not work. Following code does not works. Please, tellme what is going wrong ? Suggest any modifications in code. GMapControl1.Width=400; GMapControl1.Height=400; GMapControl1.MapType=MapC ontrol.GMapType.MAP; GMap Control1.ScrollControlTyp e=MapControl.GMapScrollCo ntrol.LARGE ; GMapControl1.ShowMapTypeC ontrol=true; GMapControl1 .GoogleMapKey=Configurati onSettings.AppSettings["D evKey"]; GPoint myPoint= new GPoint(36.1645,-86.7811); GPoint myPoint2= new GPoi nt(36.224264,-85.928273); string sFormattedHtml="Na shville<img src=D:\\Ma pPoint\\SourceCode_Murkot h0401\\SourceCode\\Sample Solution\\images\\image.g if /><a href= >Visit Nashville "; // string sFormattedHtml = "hello"; GMarker myMarker= new GMarker(myPoint); G...
read & respond »
Sai wrote: There is a change in google api and this shows a javascript error. So please remove "this.reOrderOverlays();" from GenerateNewOverLayFu nction() in JScriptGenerator.cs file. You may find more info on this at http://groups.goo gle.com/group/Google-Maps -API/browse_thread/thread /96fe322280299e0b
read & respond »
baybay wrote: This article is horrible. Very generic. Don't waste your time.
read & respond »
fabrice wrote: How do you deal with events ? like moveend or dragend ? Cheers
read & respond »
Derek wrote: Here's the fix for the marker issue that everyone seems to still be having a problem with. In JScriptGenerator.cs replace sOverLayFunction. Append("try{this.overlays .push(a[i]); \n"); with sOverLayFunction.Append(" try{this.addOverlay(a[i]) ; \n"); the overlays.push is what looks to be causing the problem. After making this fix, I can lay markers on the map. Cheers
read & respond »
Josh wrote: Patrick - Here is good easy to use control with full functionality. I did have a problem in deployment with the key, so I would recommend testing it on your server before you do a lot of development.
read & respond »
Patrick wrote: Hi Jeevan, What an excellent tutorial and powerful tool. I spent many hours trying to find where the fix for the markers and line overlays might be, but (like everyone who has filled out 4 pages of feedback pleading for help with this) I was unable. I am not so great with Javascript, but read the rest of your code with great interest. I have looked far and wide for a similar tool, and although several exist they either use a newer version of .net from me or have some such other problem. Yours works beautifully except for the known issues. What are we, the less than Code Grand Wizards, to do in order to convince Jeevan to rework the tool. Could we put a PayPal donation box on the site and bribe you to do it? Could we set the code up as a project on sourceforge.net and try to rework it that way? Coul...
read & respond »
Jeevan wrote: Hi Josh, The control when written in 2005 was made to work with Google maps Beta 1. The current version is version 2. I assume that google has made some changes to the way markers are being displayed, hence some of you are having issues in getting them to display. I haven't had a chance to update the control for the new version.Since the source code is available, I'd encourage you to take a look at it. Thanks
read & respond »
Josh wrote: Great, but I kind of need to display markers. Its actually the key part of displaying the map. After playing around with this a while, markers or custom markers will not display. Several others had the same problem. Any ideas, or just skirting the issue?
read & respond »
Eric wrote: Where do I go to download the GMap Control. I was lost trying to follow the step.
read & respond »
san wrote: I have downloaded GMap control and sample applications. But OverlayMarker and OverlayLine does not work. Following code does not works. Please, tellme what is going wrong ? Suggest any modifications in code. GMapControl1.Width=400; GMapControl1.Height=40 0; GMapControl1.MapTyp e=MapControl.GMapType.MAP ; GMapControl1.ScrollC ontrolType=MapControl.GMa pScrollControl.LARGE ; GMapControl1.ShowMapTy peControl=true; GMapCo ntrol1.GoogleMapKey=Confi gurationSettings.AppSetti ngs["DevKey"]; GPoint myPoint= new GPoint(36.1645,-86.7811); GPoint myPoint2= new G Point(36.224264,-85.92827 3); string sFormattedH tml="Nashville<img src =D:\\MapPoint\\SourceCode _Murkoth0401\\SourceCode\ \SampleSolution\\images\\ image.gif /><a href= >Visit Nashville "; // string sFormattedHtml = "hello"; ...
read & respond »
Priya wrote: I am getting an error in reOrderOverlays(). It says object dosen't support this property. I am getting a java script error. Is there a fix for this? Please let me know.
read & respond »
Rhys wrote: This looks awfully plaguerised from an article at another site... http://www.codepr oject.com/aspnet/LatLaysF lat-Part1.asp Naughty, naughty, very naughty!
read & respond »
Troy Johnson wrote: Anyone know if this is or will soon be updated to use GMap2?
read & respond »
Niketa wrote: this code is working fine but i am not able to draw lines and could not use marker. please help me in this. i had to commen reOrderOverlays() funstion call as my code was not working . please suggest me how can i resolve this. Thanks a lot.
read & respond »
Ridhi wrote: Thanks Jeevan , but i am not able to see marker and polylines or lines using this tool , please help me in this . i have tried simple code . i had to comment reOrderOverlays() to make this tool working. Please suggest the way to resolve it or problem.
read & respond »
Tom wrote: Thanks for this tool Jeevan, unfortunately I can't seem to get any markers to display (have tried the sample code as well as different browsers). No errors, just no markers! I noticed some others had this issue. Do you have any idea what may be causing this as I'd love to be able to use it properly! Many thanks Tom.
read & respond »
MICROSOFT .NET LATEST STORIES
Icahn Moves To Force Microsoft & Yahoo Together
Corporate raider Carl Icahn started his proxy fight for control of Yahoo this morning, beginning with the classic Icahn opening, the letter of reproach to the Yahoo board telling them they have acted 'irrationally and lost the faith of shareholders and Microsoft.'
"RIA" vs "Rich Client Platform": The Term Is Now Up for Debate
'RIA' is slowly fading in terms of its definition. When I first started the RIA Evangelism role in Microsoft, I had this nagging feeling that the term RIA was just all over the place. Depending on which technology you are backing and which stream of alliance you uphold, the truth is th
Book Review: ASP.NET 2.0
ASP.NET developers are bored with traditional books that outline concepts in a lengthy way. These books are good if you like to learn the features in a detailed manner. However, by the time the book is read, a new version will be released. Hence, many learners including myself prefer s
Peer Networking Series - A Closer Look at PNRP vs. Bonjour/ZeroConf
It seems as though whenever I bring up PNRP and its benefits, I am immediately inundated with a list of questions or comments indicating that Microsoft is re-inventing the wheel and that PNRP has already been implemented before in the form of ZeroConf and, more specifically, Apple's im
db4o Open Source Object-Oriented Database Supports LINQ
db4objects has announced that its db4o object database is now optimized for Microsoft's LINQ. With the new support, developers can choose an object-oriented optimized engine without changing the API or compromising performance. db4object's db4o database offers a persistence solution to
SUBSCRIBE TO THE WORLD'S MOST POWERFUL NEWSLETTERS
SUBSCRIBE TO OUR RSS FEEDS & GET YOUR SYS-CON NEWS LIVE!
Click to Add our RSS Feeds to the Service of Your Choice:
Google Reader or Homepage Add to My Yahoo! Subscribe with Bloglines Subscribe in NewsGator Online
myFeedster Add to My AOL Subscribe in Rojo Add 'Hugg' to Newsburst from CNET News.com Kinja Digest View Additional SYS-CON Feeds
Publish Your Article! Please send it to editorial(at)sys-con.com!

Advertise on this site! Contact advertising(at)sys-con.com! 201 802-3021

SYS-CON FEATURED WHITEPAPERS

ADS BY GOOGLE
BREAKING NEWS FROM THE WIRES
XtremeNotebooks Releases First Xeon Quad Core Laptop to the United States
XtremeNotebooks, first to introduce the Quad Core laptop to the United States, offers the firs