Click here to Skip to main content
15,860,972 members
Articles / Web Development / ASP.NET
Article

Lat Lays Flat - Part 1 : A Google Maps .NET Control

Rate me:
Please Sign up or sign in to vote.
4.76/5 (69 votes)
17 Oct 20056 min read 904.7K   17.3K   258   207
An ASP.NET server control wrapper for the Google Maps API.

Introduction

This is the first article in a three article series examining a custom ASP.NET server control I developed to make using the Google Maps API easier for .NET developers. This article assumes you are somewhat familiar with Google Maps (or are at least somewhat curious). If you’re not familiar with Google Maps or its sweet API checkout this site and this one for the low-down. You may see references throughout the article to "my control, my GoogleMaps control, my GMap control, etc.". I did not create the Google Maps API, I merely created a wrapper for ASP.NET using C#, XML, and XSL.

Normally my first article would focus on creating the control. But you really don’t need to understand how the control was made to start using it. I’m really anxious to get feedback about this control so rather than make you sit through the boring "creation" article first; you get the practical stuff now.

As I stated above, my main goal for this control was to make it easy to use a Google Map using .NET languages. I also tried very hard not to use any fancy or proprietary "hacks" or workarounds when creating this control.

Setup and configuration

I need to point out a few quick things before we get to the examples. The Google Maps Documentation makes some specific recommendations for the DOCTYPE, HTML namespaces, and STYLES for your Google Map pages. Each of the example pages starts like so:

HTML
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 
  "<A href="http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd</A>">
<html xmlns="<A href="http://www.w3.org/1999/xhtml">http://www.w3.org/1999/xhtml</A>" 
  xmlns:v="urn:schemas-microsoft-com:vml">
  
<head>
    <meta http-equiv="content-type" 
          content="text/html; charset=UTF-8"/>
    <title>. . .</title>
    <style type="text/css">
      v\:* 
      {
        behavior:url(#default#VML);
      }
    </style>
    . . .
</head>

Note the "strict" DOCTYPE, the custom xmlns attributes in the HTML tag, and the cryptic looking style sheet entry for v\:*. If you don’t include these values in your pages, strange things may happen. I noticed them especially when using polylines in Internet Explorer.

Google API Key

You’ll need a valid Google API key (get one here) to run the examples. The key included in the downloadable code (see the web.config file) will work as long as your application is located at http://localhost/TestWeb/.

Web.Config setup

The GMap control is based on the "div" tag. Unfortunately, ASP.NET renders div tag controls as tables in non-IE browsers by default. In order for the control to render properly in FireFox, you need to add the following entries to your web.config or machine.config file:

HTML
<browserCaps>
  <case match="^Mozilla/5\.0\s*([^)]*\))\s*(Gecko\/\d+)\s*Firefox\/
    (?'version'(?'major'\d+)(?'minor'\.\d+)(?'letters'\w*)).*">
    
    type=Firefox/${version}
    version=${version}
    majorversion=${major}
    minorversion=${minor}
    frames=true
    tables=true
    cookies=true
    javascript=true
    javaapplets=true
    ecmascriptversion=1.5
    w3cdomversion=1.0
    css1=true
    css2=true
    xml=true
    tagwriter=System.Web.UI.HtmlTextWriter
    <filter match="^b" with="${letters}">
      beta=true
    </filter>
  </case>
</browserCaps>

It’s a good idea in general to add these values to the machine.config file on your web server. Why? So things like asp:panel and other "div" based controls will render properly in FireFox.

The good stuff

Included in the downloadable code (see Download source files above) is a web project called TestWeb with nine (9) example pages on how to use my GMap control in your applications (see all examples here). The download includes the complete source for the control which I will cover in more detail in Part 3 of this article series.

Basics.aspx

__Show Me__ This is the simplest use of a GMap. Here we are just creating a GMap with a width of 500px and height of 300px. What could be simpler?

HTML
<form id="Form1" method="post" runat="server">
  <wcp:GMap runat="server" id="gMap" 
                 Width="500px" Height="300px" />
</form>

Basics.aspx.cs

To initialize the map, you’ll always want to make a call to CenterAndZoom. Otherwise, you may just get a big grey box.

C#
protected GMap gMap;

private void Page_Load(object sender, System.EventArgs e)
{
  gMap.CenterAndZoom(new GPoint(-122.141944F, 37.441944F), 4);
}

Houston, we have a GMap!

Controls.aspx.cs

__Show Me__ The .aspx code for the Controls example is identical to the Basics example. Here we are adding some basic controls to our map:

C#
protected GMap gMap;

private void Page_Load(object sender, 
                               System.EventArgs e)
{
  gMap.AddControl( new GSmallMapControl());
  gMap.AddControl( new GMapTypeControl());
  gMap.CenterAndZoom(new GPoint(-122.141944F, 
                                     37.441944F), 4);
}

GMap and GMarker events

Now let’s say you want to tap into some of the events provided by the Google Maps API. You can access any of the GMap events by implementing the proper JavaScript functions in your page. The events are outlined below and demonstrated in the following examples:

Event HandlerNotes
GMap_Click(overlay, point)"this" will reference the GMap being clicked.
GMap_Move()"this" will reference the GMap being moved.
GMap_MoveStart()"this" will reference the GMap being moved.
GMap_MoveEnd()"this" will reference the GMap that was moved.
GMap_Zoom(oldZoomLevel, newZoomLevel)"this" will reference the GMap being zoomed.
GMap_WindowOpen()
GMap_WindowClose()
GMap_AddOverlay(overlay)"this" will reference the GMap to which the overlay was added.
GMap_RemoveOverlay(overlay)"this" will reference the GMap which lost the overlay.
GMap_ClearOverlays()"this" will reference the GMap being cleared.
GMarker_Click()"this" will reference the GMarker that was clicked.
GMarker_InfoWindowOpen()
GMarker_InfoWindowClose()

Listeners.aspx

__Show Me__

HTML
<script type="text/javascript">
    function GMap_MoveEnd()
    {
      var center = this.getCenterLatLng();
      var latLngStr = 
         '(' + center.y + ', ' + center.x + ')';
      document.getElementById('message').innerHTML = 
                                           latLngStr;
    }
</script>
</head>
<body>
  <form id="Form1" method="post" runat="server">
    <wcp:GMap runat="server" id="gMap" 
                    Width="500px" Height="300px" />
    <asp:Label Runat="server" ID="message" />
  </form>
</body>

Here we are implementing one of the GMap JavaScript event functions, GMap_MoveEnd. This function will run anytime the user stops moving the GMap with their mouse. The JavaScript code gets the current center coordinate of the map (this), formats the values and displays them in the "message" label.

InfoWindow.aspx.cs

__Show Me__ This example opens the GMap Info Window and displays "Hello World". Note this examples uses JavaScript to create a new DOM text node. GMap also supports OpenInfoWindowHtml which accepts a string of HTML to display in the info window.

C#
protected GMap gMap;

private void Page_Load(object sender, 
                               System.EventArgs e)
{
  GPoint gp = new GPoint(-122.141944F, 37.441944F);
  gMap.CenterAndZoom(gp, 4);
  gMap.OpenInfoWindow(gp, 
         "document.createTextNode('Hello World')");
}

Overlays.aspx.cs

__Show Me__ What fun is a map without points of interest or line annotations? You can add "overlays" to your GMap programmatically. Currently the only two overlays provided by the Google Maps API are the GMarker and GPolyline. This example shows the usage of both:

C#
protected GMap gMap;

private void Page_Load(object sender, System.EventArgs e)
{ 
  gMap.AddControl(new GSmallMapControl());
  gMap.AddControl(new GMapTypeControl());
  GPoint gp = new GPoint(-122.141944F, 37.441944F);
  gMap.CenterAndZoom(gp, 5);

  GMarker gm = new GMarker(gp, "FirstMarker");
  gMap.Overlays.Add(gm);

  GPolyline gPoly = new GPolyline();
  gPoly.Weight = 5;
  gPoly.Opacity = 0.25F;
  gPoly.Color = Color.Red;
  for( int i=1; i<6; i++ )
  {
    float x = gp.X + (0.005F*-i);
    float y = gp.Y + (0.005F*-i);
     
    gPoly.Points.Add(new GPoint(x, y));
  }
  gMap.Overlays.Add(gPoly);
}

ClickHandling.aspx

__Show Me__ You can also capture the GMap click event and take any desired actions based on the click, like adding or removing an overlay:

HTML
<script type="text/javascript">
    function GMap_Click(overlay, point)
    {
      if( overlay )
        this.removeOverlay(overlay);
      else if( point )
        this.addOverlay(new GMarker(point));
    }
</script>
</head>
<body>
  <form id="Form1" method="post" runat="server">
    <wcp:GMap runat="server" id="gMap" 
                    Width="500px" Height="300px" />
  </form>
</body>

MarkerInfoWindow.aspx

__Show Me__ You can also capture the GMarker click event and show an info window over the marker with any HTML you want:

HTML
<script type="text/javascript">
    function GMarker_Click()
    {
      var html = "<b>" + this.id + "</b>";
      this.openInfoWindowHtml(html);
    }
</script>
</head>
<body>
  <form id="Form1" method="post" runat="server">
    <wcp:GMap runat="server" id="gMap" 
                    Width="500px" Height="300px" />
  </form>
</body>

MarkerInfoWindow.aspx.cs

Create the GMarker programmatically using any .NET language. Set each GMarker’s Id so it will be displayed in client-side when clicked.

C#
protected GMap gMap;

private void Page_Load(object sender, System.EventArgs e)
{
  GPoint gp = new GPoint(-122.141944F, 37.441944F);

  GMarker gm = new GMarker(gp, "FirstMarker");
  gMap.Overlays.Add(gm);

  gm = new GMarker(new GPoint(gp.X + 0.005F, 
                    gp.Y + 0.005F), "SecondMarker");
  gMap.Overlays.Add(gm);

  gMap.CenterAndZoom(gp, 4);
}

Icons.aspx

__Show Me__ The GMap control also supports custom icons. Creating icons requires a little more work, unless you have access to the proper images. We’ll borrow some of Google’s for demonstration purposes.

HTML
<script type="text/javascript">
    function GMarker_Click()
    {
      var html = "You clicked me!";
      this.openInfoWindowHtml(html);
    }
</script>
</head>
<body>
  <form id="Form1" method="post" runat="server">
    <wcp:GMap runat="server" id="gMap" 
                    Width="500px" Height="300px" />
  </form>
</body>

Icons.aspx.cs

Again, the theme here is programmatically creating Google API objects and interacting with them using C#/VB.NET.

C#
protected GMap gMap;

private void Page_Load(object sender, System.EventArgs e)
{
  GPoint gp = new GPoint(-122.141944F, 37.441944F);

  GIcon tiny = new GIcon();
  tiny.Id = "tiny";
  tiny.Image = new Uri(
    "http://labs.google.com/ridefinder/images/mm_20_red.png");
  tiny.Shadow = new Uri(
    "http://labs.google.com/ridefinder/images/mm_20_shadow.png");
  tiny.IconSize = new GSize(12, 20);
  tiny.ShadowSize = new GSize(22, 20);
  tiny.IconAnchor = new GPoint(6, 20);
  tiny.InfoWindowAnchor = new GPoint(5, 1);
  gMap.Icons.Add(tiny);

  gMap.AddControl(new GSmallMapControl());
  gMap.AddControl(new GMapTypeControl());
  gMap.CenterAndZoom(gp, 4);

  GMarker gm = new GMarker(gp, "TinyMarker", tiny.Id);
  gMap.Overlays.Add(gm);
}

DataListExample.aspx

__Show Me__ This is the final example that I wanted to throw into this article. I wanted to demonstrate just how easily you could create multiple GMap controls. This example creates six (6) maps centered at the same point each with a different zoom level.

HTML
<body>
  <form id="Form1" method="post" runat="server">
    <asp:DataList Runat="server" ID="dlMaps" 
      RepeatDirection="Horizontal" 
      RepeatColumns="2" RepeatLayout="Table">
      <ItemTemplate>
        <wcp:GMap runat="server" ID="gMap" 
              width="400px" height="240px" />
        <asp:Label Runat="server">
          Location: (-122.141944, 37.441944) Zoom Level:
            <%# Container.DataItem %>
        </asp:Label>
      </ItemTemplate>
    </asp:DataList>
  </form>
</body>

DataListExample.aspx.cs

Here we get a little fancy by creating an ArrayList of zoom values. This ArrayList serves as the DataSource for our DataList. During the DataBinding, we get a reference to each GMap and center it at the given point and zoom out by one step each time.

C#
protected DataList dlMaps;
private const int MAX_ZOOM = 6;

private void Page_Load(object sender, 
                        System.EventArgs e)
{
  ArrayList al = new ArrayList();
  for( int i=1; i<=MAX_ZOOM; i++ )
    al.Add(i);

  dlMaps.DataSource = al;
  dlMaps.DataBind();
}

private void dlMaps_ItemDataBound(object s, 
                       DataListItemEventArgs dliea)
{
  GMap map = (GMap)dliea.Item.Controls[0];
  int zoom = Convert.ToInt32(dliea.Item.DataItem);
  map.CenterAndZoom(new GPoint(-122.141944F, 
                                37.441944F), zoom);
}

Conclusion

In this article we covered the basic usage of my .NET GMap control. There are a lot more neat features that I consider more advanced that will be covered in Part 2 of this article series. Here is a little preview of the coming attractions:

  • Overlay data binding – Bind your database lat/lng values directly to a GMap as overlays.
  • Client Call Backs – Run server side code as a result of client side GMap events.
  • GMap postback sate – Get some data about your GMap after a postback.

In Part 3 I will discuss how I designed the GMap control and the reason for some of my design decisions (when XSL is involved there better be a damn good reason).

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Software Developer (Senior)
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralMy vote of 5 Pin
riodejenris13-Mar-12 22:49
riodejenris13-Mar-12 22:49 
QuestionHow about ASP.NET 3.5 ??? Pin
ttgttg3-Jan-12 3:29
ttgttg3-Jan-12 3:29 
GeneralMy vote of 3 Pin
shabana nazeerbatcha31-Jan-11 22:03
shabana nazeerbatcha31-Jan-11 22:03 
GeneralLat Lays Flat - Part 1 web custom control does not work Pin
aloksinha843-Aug-10 18:57
aloksinha843-Aug-10 18:57 
QuestionHi Pin
saqib ahmed27-Mar-10 23:04
saqib ahmed27-Mar-10 23:04 
GeneralMy vote of 1 Pin
Member 413351510-Mar-10 4:32
Member 413351510-Mar-10 4:32 
GeneralUrgent : How to use client id insted of map api key (Premier user) Pin
Bhavesh Mandaliya14-Dec-09 1:42
Bhavesh Mandaliya14-Dec-09 1:42 
GeneralASP.NET Mobile Controls [Google Maps & Markers] Pin
Amimpat25-Oct-09 23:01
Amimpat25-Oct-09 23:01 
QuestionGoogle Maps Pin
Antonio Mira20-Oct-09 10:15
Antonio Mira20-Oct-09 10:15 
GeneralGoogle Maps Web Control for ASP.NET with VB (not Visual C#) Pin
Steven Kilbert10-Oct-09 10:21
Steven Kilbert10-Oct-09 10:21 
Generalvb.net Pin
mbaocha4-May-09 16:45
mbaocha4-May-09 16:45 
GeneralGoogle Map:Problem with Marker Pin
0905v492-Mar-09 19:52
0905v492-Mar-09 19:52 
GeneralEmbedding maps in email Pin
Rohit Dixit5-Feb-09 22:00
Rohit Dixit5-Feb-09 22:00 
GeneralC# LatLaysFlat-Part1 to 3 Pin
oz3fi26-Aug-08 22:15
oz3fi26-Aug-08 22:15 
GeneralRe: C# LatLaysFlat-Part1 to 3 Pin
melntess9-Nov-08 21:23
melntess9-Nov-08 21:23 
Generalv2- api not working Pin
kavyaasas12-Aug-08 5:10
kavyaasas12-Aug-08 5:10 
GeneralA question Pin
yakida21-Jul-08 4:17
yakida21-Jul-08 4:17 
QuestionCan provide me some useful URL + C# source code for google map. Pin
ifah8-May-08 19:35
ifah8-May-08 19:35 
AnswerRe: Can provide me some useful URL + C# source code for google map. Pin
rpedersen11-May-08 7:39
rpedersen11-May-08 7:39 
GeneralRe: Can provide me some useful URL + C# source code for google map. Pin
transoft5-Feb-09 16:32
transoft5-Feb-09 16:32 
GeneralRe: Can provide me some useful URL + C# source code for google map. Pin
rpedersen7-Feb-09 5:19
rpedersen7-Feb-09 5:19 
GeneralRe: Can provide me some useful URL + C# source code for google map. Pin
transoft9-Feb-09 2:22
transoft9-Feb-09 2:22 
GeneralRe: Can provide me some useful URL + C# source code for google map. Pin
rpedersen9-Feb-09 7:40
rpedersen9-Feb-09 7:40 
GeneralRe: Can provide me some useful URL + C# source code for google map. Pin
transoft9-Feb-09 10:33
transoft9-Feb-09 10:33 
QuestionUnable to display WCPierce google map in my localhost?? Pin
ifah8-May-08 19:07
ifah8-May-08 19:07 

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.