Cutout: The GMAP control lets .NET developers use Google maps functionality as a server-side control by writing little or no JavaScript

baasopchoppySecurity

Nov 5, 2013 (3 years and 7 months ago)

89 views

Google Maps and ASP.NET

Building a Custom Server Control

Jeevan .C. Murkoth

1

Cutout: The GMAP control lets .NET developers use Google maps
functionality as a server
-
side control by writing little or no
JavaScript




Google Maps & ASP.NET

Building a custom server control


by Jeevan C. Murkoth


I’m sure that most of you have heard a
bout or 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 can drag and zoom maps from a Web browser. In many ways
it has heralded the arrival of AJAX (Asy
nchronous JavaScript and
XML), which I’m sure will revitalize Web development in the
days to come. What makes the service even better is the
availability of the Google Maps API as a free beta service. The
API allows developers to embed Google Map in their
custom apps.
It also lets them overlay information on the map and customize the
map to their needs. As I write this article there are quite a few sites
that use Google Maps and more and more of them are appearing by
the day.

The API by itself is pretty st
raightforward and easy to use,
however it requires the developer to have a good command of
JavaScript sonce it relies extensively on client
-
side Java scripting.
In this article, we’ll be looking at building a custom ASP.NET
server control that will let the

.NET developer harness the power of
Google Maps in the code behind model. We’ll see how to use most
of the functionality exposed by Google Maps with this control and
how to data bind the control so developers can easily build data
-
driven custom ASP.NET We
b applications. The control would
eliminate the need for the developer to write any JavaScript to use
most of the Google Map functionality.

Google Maps and ASP.NET

Building a Custom Server Control

Jeevan .C. Murkoth

2


Some Google Maps Basics

Before we get into the details of the ASP.Net control, let’s look
at the basics of the Goog
le Maps API. A detailed description of the
API can be found at
http://www.google.com/apis/maps/documentation/
. Before using
Google Maps, the first step is to register for a key with Google
(
http://www.google.com/apis/maps/signup.html
). This is
absolutely free and just 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 before you start using Google Maps
in your application
(http://www.google.com/apis/maps/terms.html).

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’s
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 the hybrid
view that combines map and satellite views. The other controls that
are u
sually seen on the map are the ones used to add scrolling and
zooming capability to the map. When this article was written, there
were three different controls available:


A.

GlargeMapControl, a large control for scrolling and zooming.

B.

GSmallMapControl, like
the previous one but eliminates the
zoom scale bar.

C.

GsmallZoomControl, which includes only Zooming controls.


Once a map has been set up, it’s possible to overlay information
on it. The information can be in the form of points or lines, points
being the mo
st common. To overlay a point on a Google Map, it’s
necessary to know its longitude and latitude. Google currently
doesn’t provide any geo coding services that give the co
-
ordinates
corresponding to an address, but there are a couple of free services
Google Maps and ASP.NET

Building a Custom Server Control

Jeevan .C. Murkoth

3

on th
e Internet that do. Geocoder.us is one of them and given a
U.S. address, it returns its longitude and latitude.

With the longitude and latitude in hand, 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. To center and zoom on a point, the
GMap Object exposes a ZoomandCenter method that takes the
point and the level of zoom required as the parameter. Just like
points, it’s possib
le 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. To add a line to the Google Map, we
need to create an instance of a GPolyLine object and pass in an
array of GPo
ints to plot it. It’s 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 po
-

up window “InfoWindow.”


GMAP Control


The main aim of GMAP control is to let .NET developers use
the functionality of Google maps as a server
-
side control by
writing little to no JavaScript at all. It’s more of a .NET wrapper
around the Google API. However, since it’s a full
-
fledged
ASP.NET s
erver
-
side control, it’s possible to bind data to the
control and increase the usability of Google Maps. Below we’ll see
how to use this control to implement most of the common
functionality of Google Maps. Before we do, let’s take a look at
the control. I
ts principal class is the “GMapControl” class. This
class in turn references the classes below. Most of these classes are
.NET equivalents of the classes used by Google:


1.

GPoint


It’s the class representation of a geographical point
and exposes latitude a
nd longitude as its two properties

2.

GPoints

It represents a collection of GPoint objects.

Google Maps and ASP.NET

Building a Custom Server Control

Jeevan .C. Murkoth

4

3.

GIcon


Represents a custom icon that’s used as an overlay
on a map. The GIcon class exposes the following properties:
The Image URL that, as the name suggests, is th
e URL of the
image used to represent the Icon and ShadowImageURL, the
URL of the shadow associated with the icon. The other
properties are the IconSize and ShadowSize that represent the
size of the icon and the shadow. The last two properties are
IconAncho
r and InfoWindowAnchor, which specify the point
where the icon should be anchored to the map relative to its
top left corner and point where the InfoWindow should be
anchored to the map.

4.

GLine


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’s also possible to set the color
of the line, its weight, and opacity through an overloaded
constructor.

5.

GMarker

This is the .NET representation of the Google
Maps class GMar
ker. 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 wants to use a custom icon to represent the
marker.

6.

Gsize


It represents a two
-
dimensi
onal size measurement.

7.

JScriptGenerator


This is an internal class and has more of a
helper function. It generates most of the JavaScript functions
needed by the control

8.

HelperColorConvertor


The class is used to convert a color
into its equivalent Hex v
alue. This class is marked as
internal.

9.

HelperDataResolver


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.


Google Maps and ASP.NET

Building a Custom Server Control

Jeevan .C. Murkoth

5

The help file that describes
the different methods and
properties of the classes involved in detail 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 have 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 browsers like Netscape and Firefox,
include the following
browser cap section in your app’s Web config file. Listing 1 shows
the browser cap section.


Page Configuration

Google has certain recommendations for the HTML
standards on pages that contain a map to make sure that the layout
is pred
ictable across different browsers described in detail in the
Google Maps documentation. It’s 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 have to include the VML
na
mespace in the HTML page for Internet Explorer browsers.
Make sure you don’t forget to do this or the lines won’t be
displayed. The HTML tag of your page should at a minimum look
like the snippet below.


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


Google Maps and ASP.NET

Building a Custom Server Control

Jeevan .C. Murkoth

6

Addi
ng to the Toolbar

This step is optional. However, if you’re using Visual Studio
.NET as your IDE, I’d recommend that you go ahead and add the
GMap control to your toolbox. The advantage to doing so is that
you can easily drag
-
and
-
drop the GMAP control onto

an ASPX
page like any other ASP.NET control. Visual Studio will
automatically register the control on your page. The Figure 3
below shows the GMAP control on my toolbar.



Figure 3

GMAP control on the toolbar in VS.NET

Creating a Basic Map Using the Cont
rol

Since we’re done with the set
-
up, let’s go ahead and create a
simple example using the control. We’ll add the GMAP control to
the page, set its dimensions and make it center and zoom at a
particular point. For our sample application, I’ve saved the map

key in the Web.Config file and will be setting the GoogleMapKey
property of the control from the config file. I’ll be setting the map
type of the control to “Map.” In case no map type is specified, the
control defaults to the preset “Map.” The GMAP contro
l also
supports satellite and hybrid map types. Make sure that you center
and zoom at a point or otherwise all that shows up will be a grey
Google Maps and ASP.NET

Building a Custom Server Control

Jeevan .C. Murkoth

7

area. The code below shows this example and Figure 3 shows the
output


private

void

Page_Load(
object

sender,
System
.EventArgs e)



{




GMapControl1.Width=400;

GMapControl1.Height=400;

GMapControl1.MapType=MapControl.GMapTyp
e.MAP;

GMapControl1.GoogleMapKey=ConfigurationSe
ttings.AppSettings["DevKey"];

GMapControl1.CenterAndZoom(
new

GPoint(36.224264,
-
86.628273),9);


}


Google Maps and ASP.NET

Building a Custom Server Control

Jeevan .C. Murkoth

8


Figure 3

Output in the Web browser


Setting the GMAP Control Properties



To the basic example we just created, let’s go ahead and set a
couple of properties. The GMAP control exposes a set of
properties that lets the developer customize the control to hi
s or her
needs. If we want to give the user the flexibility to change the
view, we set the control’s
ShowMapTypeControl
property to true.
By default, the user can drag the map. However, if we don’t want
the user to drag the map around, we can set the
Enabl
eDragging
property to false. To let the user scroll or zoom, set the control
’s
Google Maps and ASP.NET

Building a Custom Server Control

Jeevan .C. Murkoth

9

ScrollControlType

property. There are three different options.
“Large,” “small,” and “zoom only” correspond to the controls
offered by Google. The source code is below and Figur
e 4 shows
the output in the browser.


private

void

Page_Load(
object

sender,
System.EventArgs e)



{




GMapControl1.Width=400;




GMapControl1.Height=400;

GMapControl1.MapType=MapControl.GMapTyp
e.MAP;
GMapControl1.ScrollControlType=MapControl.
GMapScrollC

ontrol.LARGE ;




GMapControl1.EnableDragging=
false
;

GMapControl1.ShowMapTypeControl=
true
;
GMapControl1.GoogleMapKey=ConfigurationSe
ttings.AppSettings["DevKey"];

GMapControl1.CenterAndZoom(
new

GPoint(36.224264,
-
86.628273),9);



}





Figure 4

Output in th
e Web browser


Overlaying Markers & Pop
-
up Windows


Another cool feature of Google Maps is the ability to display
markers on the map and attach pop
-
up windows to these markers
on the click event. It’s possible to display formatted HTML
containing links and

images in these pop
-
up windows. Let’s see
how to do the same using the GMAP ASP.NET control. Let’s take
Google Maps and ASP.NET

Building a Custom Server Control

Jeevan .C. Murkoth

10

the previous example and modify it to add two markers. One
would be a plain marker and the other would have a pop
-
up
window, which would display some t
ext. The GMAP ASP.NET
control has an overloaded method called
OverlayMarker
that takes
the formatted HTML as a string parameter. If the overloaded
method is called and some HTML is passed to the method, a click
event is automatically sent to the marker and

the InfoWindow is
displayed. The code to overlay two markers is in Listing 2 and
Figure 5 shows the output.



Figure 5

Output in the Web browser


Google Maps and ASP.NET

Building a Custom Server Control

Jeevan .C. Murkoth

11

Overlaying Custom Markers


Google gives us the flexibility to replace its standard marker
icon with any cus
tom icon we specify. The same functionality is
provided by the GMAP ASP.NET control. To do so, we have to
define a GIcon Class with at least the following properties:





URL of the image that would represent the GIcon.



URL of the shadow image.



Size of the i
mage



Size of the shadow



The point at which the icon is to be anchored to the icon.


In case InfoWindows are used, it’s also necessary to specify the
point where the InfoWindow is to be anchored to the map. For this
example we’ll borrow the icons from Goog
le’s Ride Finder
application. Let’s take the same two points that we used in the
marker example and replace the standard marker icons with these
custom icons. The code in Listing 3 is same as in Listing 2 except
for the use of custom icons. Figure 6 shows
the output.


Google Maps and ASP.NET

Building a Custom Server Control

Jeevan .C. Murkoth

12


Figure 6

Output showing custom markers


Overlaying Lines


In this section, we’ll see how to overlay a line on a Google
Map. Lines can be overlaid on maps to denote routes, boundaries,
or some other specific purpose a developer may deem neces
sary.
As in the Google Maps API, the GMAP ASP.NET control allows
an overlay of lines. In the GMAP control, the GLine class
represents a line and takes a collection of GPoints to plot a line
through them. It’s also possible to set the color, width, and opac
ity
Google Maps and ASP.NET

Building a Custom Server Control

Jeevan .C. Murkoth

13

of the line. While the Google Map API requires color to be passed
in as a Hex value, the GMAP control takes in a
System.Drawing.Color structure, making it easier to set the color
by name. Listing 4 shows the code and Figure 7 shows the
rendering



Fig
ure 7

Rendering the line in the browser


Using Multiple Google Map Controls in a Page


So far in all the examples we’ve used only one instance of
the control in a page. It’s possible to have any number of GMAP
Google Maps and ASP.NET

Building a Custom Server Control

Jeevan .C. Murkoth

14

controls on a single page and have granular co
ntrol over each of
them. In this example, we have four instances of the control and
will center and zoom them on four different cities. Listing 5 shows
the code and Figure 8 shows the output in the browser. It’s
possible to have markers or lines on any of
these controls.




Figure 8

Multiple Google Map controls output


Google Maps and ASP.NET

Building a Custom Server Control

Jeevan .C. Murkoth

15

Binding Data to the Control

The GMAP ASP.NET control supports data binding and it’s
possible to bind it to any data source that implements the
IEnumerable interface, hence it can bind to mos
t of the commonly
used sources like data tables, datasets, and collections. Currently
the control only supports overlaying standard markers via data
binding. The control exposes the following properties that have to
be set before data binding.




MarkerLatit
udeField


Property used to specify which field
from the data source will bind to the latitude field of each
marker in the control.



MarkerLongitudeField


Property used to specify which
field from the data source will bind to the longitude field of
each ma
rker in the control.



MarkerText


Property used to specify which field from the
data source will bind to the text field of each marker in the
control. This is optional.



DataSource


Property used to set the source of data.


In this example we will first po
pulate a table with a point and
then bind it to the GMAP control. Listing 6 shows the code
involved in the example and Figure 9 shows the output.


Google Maps and ASP.NET

Building a Custom Server Control

Jeevan .C. Murkoth

16


Figure 9

Output


Conclusion

The Google Maps API by itself is very versatile. I hope this
control will make
it easier for .NET developers to harness its
potential.


Listing 1: Browser Cap Section

<
browserCaps
>



<
case

match
="Gecko/[
-
\
d]+">

Google Maps and ASP.NET

Building a Custom Server Control

Jeevan .C. Murkoth

17




browser=Netscape




frames=true




tables=true




cookies=true




javascript=true




javaapplets=true




ecmascriptversio
n=1.5




w3cdomversion=1.0




css1=true




css2=true




xml=true




tagwriter=System.Web.UI.HtmlTextWriter




<
case

match
="rv:1.0[^
\
.](?'letters'
\
w*)">





version=6.0





majorversion=6





minorversion=0





<
case

match
="^b"

with
="${letters}">






beta=
true





</
case
>




</
case
>




<
case

match
="rv:1(
\
.
\
d+)(
\
.
\
d)?(?'letters'
\
w*)">





version=7.0





majorversion=7





minorversion=0





<
case

match
="^b"

with
="${letters}">






beta=true





</
case
>




</
case
>



</
case
>


</
browserCaps
>


Listing 2 Overlay
ing Two Markers


private

void

Page_Load(
object

sender, System.EventArgs e)


{



GMapControl1.Width=400;

Google Maps and ASP.NET

Building a Custom Server Control

Jeevan .C. Murkoth

18



GMapControl1.Height=400;

GMapControl1.MapType=MapControl.GMapType.MA
P;
GMapControl1.ScrollControlType=MapControl.GMap
ScrollControl.LARGE ;

GMapControl
1.ShowMapTypeControl=
true
;
GMapControl1.GoogleMapKey=ConfigurationSettings.
AppSettings["DevKey"];



GPoint myPoint=
new

GPoint(36.1645,
-
86.7811);



GPoint myPoint2=
new

GPoint(36.224264,
-
85.928273);


string

sFormattedHtml="<b><font
color=red>Nashville</fon
t><b><br> </font><img
src=http://localhost/maptest/images/images.jpg
/><br><a href=http://test >Visit Nashville </a>";



GMarker myMarker=
new

GMarker(myPoint);



GMarker myMarker2=
new

GMarker(myPoint2);



//Overloaded constructor



GMapControl1.OverlayM
arker(myMarker,sFormattedHtml);



GMapControl1.OverlayMarker(myMarker2);



GMapControl1.CenterAndZoom(myPoint,9);



}


Listing 3:
Custom Markers


private

void

Page_Load(
object

sender, System.EventArgs e)


{



GMapControl1.Width=400;



GMapControl1.Height=4
00;

GMapControl1.MapType=MapControl.GMapType.MA
P;
GMapControl1.ScrollControlType=MapControl.GMap
ScrollControl.LARGE ;

Google Maps and ASP.NET

Building a Custom Server Control

Jeevan .C. Murkoth

19

GMapControl1.ShowMapTypeControl=
true
;
GMapControl1.GoogleMapKey=ConfigurationSettings.
AppSettings["DevKey"];



GPoint myPoint=
new

GPoint
(36.1645,
-
86.7811);



GPoint myPoint2=
new

GPoint(36.224264,
-
85.928273);

string

sFormattedHtml="<b><font
color=red>Nashville</font><b><br> </font><img
src=http://localhost/maptest/images/images.jpg
/><br><a href=http://test >Visit Nashville </a>";



GMark
er myMarker=
new

GMarker(myPoint);



//Creating our custom icon



GIcon myIcon =
new

GIcon();

myIcon.ImageURL="http://labs.google.com/ridefinder/i
mages/mm_20_blue.png";

myIcon.ShadowImageURL="http://labs.google.com/rid
efinder/images/mm_20_shadow.png";



my
Icon.ShadowSize=
new

GSize(22,20);



myIcon.IconSize =
new

GSize(12,20);



myIcon.IconAnchor=
new

GPoint(6,20);



myIcon.InfoWindowAnchor=
new

GPoint(5,1);



GMarker myMarker2=
new

GMarker(myPoint2);



myMarker.Icon=myIcon;



GMapControl1.OverlayMarker(myM
arker,sFormattedHtml);

myMarker2.Icon=myIcon;
myMarker2.Icon.ImageURL="http://labs.google.com/ri
definder/images/mm_20_green.png";



GMapControl1.OverlayMarker(myMarker2);



GMapControl1.CenterAndZoom(myPoint,9);


}


Listing 4:
Overlaying Lines



private

vo
id

Page_Load(
object

sender,
System.EventArgs e)

Google Maps and ASP.NET

Building a Custom Server Control

Jeevan .C. Murkoth

20



{




GMapControl1.Width=400;




GMapControl1.Height=400;

GMapControl1.MapType=MapControl.GMapTyp
e.MAP;
GMapControl1.ScrollControlType=MapControl.
GMapScrollControl.LARGE ;

GMapControl1.ShowMapTypeControl=
tru
e
;
GMapControl1.GoogleMapKey=ConfigurationSe
ttings.AppSettings["DevKey"];

// Creating the 3 points through which the line
passes




GPoint pt1 =
new

GPoint(40.631096,
-
75.488627);




GPoint pt2=
new

GPoint(35.113813,
-
85.321043);




GPoint pt3=
new

GPoint(33
.590040,
-
101.866815);




//Adding it to the points collections




GPoints ptList=
new

GPoints();




//Adding it to the points collections




ptList.Add(pt1);




ptList.Add(pt2);




ptList.Add(pt3);




//Adding the points collection to the line




GLine myl
ine =
new

GLine(ptList);




//Setting the Color , weight and Opacity




myline.LineColor=Color.Blue;




myline.Weight =3;




myline.Opacity=1;




GMapControl1.OverlayLine(myline);




GMapControl1.CenterAndZoom(pt2,14);



}


Listing 5:
Multiple Controls on
a Page

private

void

Page_Load(
object

sender, System.EventArgs e)



{

Google Maps and ASP.NET

Building a Custom Server Control

Jeevan .C. Murkoth

21




//First Control




GMapControl1.Width=200;

GMapControl1.Height=200;
GMapControl1.GoogleMapKey=ConfigurationSe
ttings.AppSettings["DevKey"];

GMapControl1.CenterAndZoom(
new

GPoint(36.2242
64,
-
86.628273),9);




//Second Control




GMapControl2.Width=200;

GMapControl2.Height=200;
GMapControl2.GoogleMapKey=ConfigurationSe
ttings.AppSettings["DevKey"];

GMapControl2.CenterAndZoom(
new

GPoint(35.07,
-
85.27),9);




//Third Control




GMapControl3.Wid
th=200;

GMapControl3.Height=200;
GMapControl3.GoogleMapKey=ConfigurationSe
ttings.AppSettings["DevKey"];

GMapControl3.CenterAndZoom(
new

GPoint(30.32,
-
97.77),9);




//Fourth Control




GMapControl4.Width=200;

GMapControl4.Height=200;
GMapControl4.GoogleMapKe
y=ConfigurationSe
ttings.AppSettings["DevKey"];

GMapControl4.CenterAndZoom(
new

GPoint(39.57,
-
75.10),9);



}


Listing 6: Data Binding in a GMAP Control

private

void

Page_Load(
object

sender, System.EventArgs e)



{




GMapControl1.Width=400;




GMapControl1.H
eight=400;

Google Maps and ASP.NET

Building a Custom Server Control

Jeevan .C. Murkoth

22




//create the datatable




DataTable dt =
new

DataTable("Databind");

dt.Columns.Add(
new

DataColumn("latitude",
typeof
(
double
)));

dt.Columns.Add(
new

DataColumn("longitude",
typeof
(
double
)));

dt.Columns.Add(
new

DataColumn("htmltext",
typeof
(
stri
ng
)));




//Filling the datatable




for
(
int

i=0; i<10;i++)




{





DataRow dr= dt.NewRow();





dr["latitude"]=36.224264+i;





dr["longitude"]=
-
86.628273+i;

dr["htmltext"]= "<b>POINTER NUM: </b>
" +i.ToString();





dt.Rows.Add(dr);









}

GMapContr
ol1.GoogleMapKey=ConfigurationSe
ttings.AppSettings["DevKey"];




GMapControl1.DataSource=dt;




//set the latitude data field




GMapControl1.MarkerLatitudeField="latitude";

//set the longitude data field




GMapControl1.MarkerLongitudeField="longitude";

/
/set the text data field




GMapControl1.MarkerText="htmltext";




GMapControl1.DataBind();

GMapControl1.CenterAndZoom(
new

GPoint(36.224264,
-
86.628273),14);



}



Google Maps and ASP.NET

Building a Custom Server Control

Jeevan .C. Murkoth

23

Reference:

1.

Google Maps API Documentation


http://www.google.com/apis/maps/documentation/

2.

Google Maps News groups


http://www.google.com/apis/maps/documentation/

3.

Essential ASP.NET (Custom Controls)


Fritz Onion