Category: Google Map API


Maps are becoming ubiquitous in web applications. They are being used as an effective and non-intrusive way of gathering geo-specific data from the user or to present geo-specific information to the user including tracking report of shipments et al. However even two years ago, embedding a map within an application was considered a specialized area requiring good understanding of Geographical Information System or GIS. But the arrival of Google Maps and its corresponding set of APIs, incidentally known as Google Map API, have changed the scenario. Now a developer having a good grasp on JavaScript, can without much ado embed an interactive map in a web-application using Google Map API. The questions that arise next is what exactly is Google Map API and what are the steps to be followed in using Google Map API. The answer to these questions is the focus of this discussion. The first section would deal with the whys and wherefores of Google Map API. In the second section I would detail the steps to use Google Map API. The last section would focus on a real world example based on the steps discussed in second section. That is the outline of the discussion.

Google Map API – What is it:

Google Map provides not only the map, satellite image or a hybrid of both but also an extensive range of operations on the map such as zooming, panning, information pop-ups, overlays etc. Google Map API provides interface into these operation through JavaScript objects. The beauty of the setup is that the functionalities work in the same non-intrusive way as the original Google Maps without developer needing to know the details of AJAX or how it is implemented in Google Maps. The developer has to just know the classes and their methods to access the services of Google Maps. The functionalities exposed by the Google Map API can be categorized as follows:

1. Configuration

2. Controls

3. Map Types

4. Map State

5. Overlays

6. Information Window

7. Map Navigation

8. Events

The accesses to most of the group of functionalities mentioned above are through the methods of GMap2 class. GMap2 class forms the basis of map creation, display and manipulation.

1. Configuration:

All the aspects of any map provided by Google Maps are configurable -be it the enabling of dragging and information windows or continuous zooming. The methods of GMap2 class sectioned under configuration enables configuration of the map. Following are the most oft used methods for configuring maps:

i. enableDragging() – enables the dragging of map. Dragging is enabled by

default.

ii. disableDragging() – disables the dragging of map.

iii. enableInfoWindow() – enables the information window

iv. disableInfoWindow() – disables the displaying of information window.

2. Controls:

The UI elements using which user controls the map and its functionalities come under controls category. There are two main methods related to controls which are:

i. addControl(control, [position]) – adds the specified control to the map at the

place specified by position parent. The position

parameter is optional.

ii. removeControl(control) – removes the specified control from the map.

Both the above functions takes instance of GControl class. There are four existing instances of GControl class – GSmallMapControl, GLargeMapControl, GSmallZoomControl, GScaleControl and GMapTypeControl. These can be passed to the addControl() method to add controls to the map.

3. Map Types:

Google Maps provide three types of map – simple map that provides outline based map, satellite map that streams the satellite imaged maps and hybrid map which is a combination of both aforementioned maps. The map types provided by Google Maps is controlled by the following methods:

i. setMapType(type) – sets the type of map to be displayed.

ii. removeMapType(type)- removes a already set map type.

The type parameter is specified using the constants provided by GMapType class. It can be G_NORMAL_MAP, G_SATELLITE_MAP, G_HYBRID_MAP corresponding to maps of type simple, satellite image based or combination of both.

4. Map State:

The methods that provide information about the state of the map comes under it. The information provided by map state methods include whether the map is loaded or not, the current focus point or center of the map etc. The commonly used methods are:

i. isLoaded() – it tells whether the map is loaded on to client browser or not

ii. getCenter() – this method provides the latitude and longitude of the center of

current viewport of the map.

5. Overlays:

By definition “A map overlay refers to a point or polyline that is added on top of the Google Map”. In essence an overlay means a point or line that is placed on the map to distinguish it from rest of the map. Mostly used methods in this category are:

i. addOverlay(overlay) – it adds an overlay presented by the overlay object

passed as parameter.

ii. removeOverlay(overlay) – it removes an overlay already added and

represented by the overlay object passed as

parameter.

The overlay object can be of type GPoint or GPolyline.

6. Information Window:

When an overlay is clicked, a window containing detailed information can be displayed. It is called the Information window or info window in short. Following are the main methods to control an info window:

i. openInfoWindow(latlng,dom,[opts]) – opens an information window at the

point specified by latlang and with the

data specified as dom which is a DOM

node.

ii. showMapBlowup(latlng,[opts]) – opens a info window at the specified as

specified latlng containing the close-up view of

the latlng specified as parameter.

The parameter latlng is of the type GLatLng.

7. Map Navigation:

The navigation of map can be controlled using the methods provided under this category. The commonly used methods are:

i. setCenter(center,[zoom],[type]) – loads the map with focus on the point

specified by center with an optional level of

zoom and type of the map.

ii. panTo(center) – it navigates to the point on the map specified by center.

iii. setZoom(level) – it zooms into or magnifies the current center to the level

specified with the parameter level.

8. Events:

Google Map API provide methods to intercept any event taking placing on the map. The common events supported by Google Map API are:

i. click – it is generated when user clicks on any point within the boundaries of the

map.

ii. move – it is fired when the map is moving or panning. During the panning it

may be fired many times.

iii. moveend – it is fired when the panning is completed.

That brings us to the end of first section. In the next section I would detail the steps required to work with Google Map API.

Using Google Map API – Step By Step:

Now that the services provided by Google Map API have been discussed, lets see the steps to use the API. To use Google Map API, two main steps have to be followed:

1. Acquiring the Registration Key

2. Setting-up the map

The second step again consists of sub-steps that actually deals with the setting up of HTML and Google Map API library.

1. Acquiring the Registration Key:

It is through the registration key that one can access the API. A key can be used within a web directory i.e. files within that directory and its subdirectories can make use of the key. To get the key, go to the site and provide the URL of the site for which the key has to be generated. The key alongwith an example would be provided which can be used as base for further developments.

2. Setting-up the map:

The Google Map API library is a JavaScript library. So its focus would be HTML and JavaScript based applications. In other words, Google Map API targets the UI for the web-applications. To set-up the page to display map the required steps can be enumerated as follows:

i. Set-up the HTML page:

The first step in displaying the map is by providing the required placeholder within the page where the map has to be shown. To do this <div> tag has to be used. It creates a logical block for the map to be displayed. For example following statement creates a placeholder named ‘map’:

<div id=”map” style=”width: 500px; height: 500px”></div>

ii. Importing/Including the Google Map API:

To use the API, its library has to be referenced. In case of JavaScript importing or including of the library (other terms for referencing a library) is done using the src attribute of <script> tag. So to include Google Map API library, the src of the <script> tag would be as follows:


<script src=”http://maps.google.com/maps?file=api&v=2&key=[yourkey]“

type=”text/javascript”></script>

The value of src attribute tells us two important points about Google Map API. First is the location of the API which is the Google’s site itself. So even for testing purpose, availability of internet is required. Second the is usage of the key provided after registration. The key is passed along with the URL in the src to tell Google that the site trying to access the API library is authorized site. Next step is to implement a function that would be called when the document is loaded. That is done by calling a function in the <body> tag’s onload handler. the statements would be :

<script type=”text/javascript”>

//<![CDATA[

function load() {

}

//]]>

</script>

For defining the function and it would be called from the body thus:

<body onload=”load()” >

:

:

</body>

The first step in implementation of logic within the function is to check whether the client browser is capable of displaying map or not. That can be done using GBrowserIsCompatible(). It return a Boolean value specifying whether the browser is capable of displaying map or not. The code block using it would be thus:

if (GBrowserIsCompatible()) {

//…

}

To display the map what we need is an object of GMap2 class. To get it, GMap2 constructor with the id of the <div> serving as placeholder, is required. For example the following code creates an instance of GMap2 class and assigns it to the variable named map:

var map = new GMap2(document.getElementById(“map”));

The last step in displaying the map is to set its focus on a particular point. That can be accomplished by calling the setCenter() method on map variable. The argument passed is of type GLatLng which, in turn accepts latitude and longitude as its parameter. The following sets the focus on the point defined by latitude 31.122027 and longitude 77.111664:

map.setCenter(new GLatLng(31.122027, 77.111664), 13);

The map object can be used to manipulate map by using the methods enumerated in first section. The last but not least point is to call GUnload() through onunload handler of body tag to prevent memory leak:

<body onload=”load()” onunload=”GUnload()”>

:

</body>

That brings us to the end of the second section. In the next section I would develop a small application that would show the different functionalities discussed in first section using the steps detailed in this section.

Google Map API – In Real World:

Now I will be building a small application that displays map using Google Map API. It does the following:

1. Display the map with Shimla (India) as its center.

2. Provide zoom and pan controls for navigation.

3. Provide map type control to change between the three map types

4. Handle the click event and display information window showing the current focus

point on click upon the map.

So lets get going. First the HTML setup:

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd”>

<html xmlns=”http://www.w3.org/1999/xhtml”>

<head>

</head>

<body onload=”load()” onunload=”GUnload()”>

<div id=”map” style=”width: 500px; height: 500px”></div>

</body>

</html>

The onload handler calls the load function which is as follows:

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd”>

<html xmlns=”http://www.w3.org/1999/xhtml”>

<head>

<script src=”http://maps.google.com/maps?file=api&amp;v=2&amp;key=[yourkey]“

type=”text/javascript”></script>

<script type=”text/javascript”>

//<![CDATA[

function load() {

}

</head>

<body onload="load()" onunload="GUnload()">

<div id="map" style="width: 500px; height: 500px"></div>

</body>

</html>

Place the key you received in place of [yourkey]. This sets up the link to Google Map API and declares the load function. Next comes the creating the map instance and setting the center.

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd”>

<html xmlns=”http://www.w3.org/1999/xhtml”>

<head>

<script src=”http://maps.google.com/maps?file=api&amp;v=2&amp;key=[yourkey]“

type=”text/javascript”></script>

<script type=”text/javascript”>

//<![CDATA[

function load() {

if (GBrowserIsCompatible()) {

var map = new GMap2(document.getElementById("map"));

map.setCenter(new GLatLng(31.122027, 77.111664), 13);

}

}

</head>

<body onload="load()" onunload="GUnload()">

<div id="map" style="width: 500px; height: 500px"></div>

</body>

</html>

Next lets add the controls:

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

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<script src="http://maps.google.com/maps?file=api&amp;v=2&amp;key=[yourkey]“

type=”text/javascript”></script>

<script type=”text/javascript”>

//<![CDATA[

function load() {

if (GBrowserIsCompatible()) {

var map = new GMap2(document.getElementById("map"));

map.addControl(new GSmallMapControl());

map.addControl(new GMapTypeControl());

map.addControl(new GScaleControl());

map.setCenter(new GLatLng(31.122027, 77.111664), 13);

}

}

</head>

<body onload="load()" onunload="GUnload()">

<div id="map" style="width: 500px; height: 500px"></div>

</body>

</html>

The controls have to be added before setting the center. The last part is to handle the click event and show the current focus point on a information window:

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

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<script src="http://maps.google.com/maps?file=api&amp;v=2&amp;key=[yourkey]“

type=”text/javascript”></script>

<script type=”text/javascript”>

//<![CDATA[

function load() {

if (GBrowserIsCompatible()) {

var map = new GMap2(document.getElementById(“map”));

map.addControl(new GSmallMapControl());

map.addControl(new GMapTypeControl());

map.addControl(new GScaleControl());

map.setCenter(new GLatLng(31.122027, 77.111664), 13);

GEvent.addListener(map,”click”, function(){

map.openInfoWindow(map.getCenter(), document.createTextNode(map.getCenter()));

}

);

}

}

</head>

<body onload=”load()” onunload=”GUnload()”>

<div id=”map” style=”width: 500px; height: 500px”></div>

</body>

</html>

That completes the application. In just few lines it does a lot. This was just a teaser of what Google Map API can do. In the next articles I would discuss about advanced features such as communicating with servers and geo-encoding. Till then….

Back again

It has been a long time since the last post. However, from now on I will be posting on a regular basis. There is a chance of changing the name of the blog as well. But thats for the future. Now its time for ranting. Yes rant. Its about GMap API.

The simple app I had created works well from my home where there is no router or proxy per se. But, when I tried it from my friend’s home pc which is behind a proxy, it started to show Paulo Alto even when I gave coordinates of India. Whats the problem here? Any idea anybody?

A quick look at events supported by GMap. GMap supports event handling through the Event listener pattern. The class that provides support for event handling is GEvent class. The addEventListener() method of GEvent class. It takes three parameters:

1. Object of GMap:

The map on which event has to be applied.

2. The event to be Handled:

It is a string. The string contains event names. There are two commonly used events:

i. click:

It is the most common of all the events. It is generated (or happens) when one presses and releases the left mouse button on the map.

ii. moveend:

It is generated when the user stops navigating or panning the map. It essentially means end of moving a map.

Following code shows how to use both types of events:

The code is a slight modification of the initial code to display map.

function load() {

if (GBrowserIsCompatible()) {

var map = new GMap2(document.getElementById(“map”));

//map.setMapType(GMapType.G_HYBRID_MAP);

map.addControl(new GSmallMapControl());

map.addControl(new GMapTypeControl());

map.addControl(new GScaleControl());

map.setCenter(new GLatLng(31.122027, 77.111664), 13);

GEvent.addListener(map,”click”, function(){

alert(map.getCenter())

}

);

//for the event moveend

GEvent.addListener(map,”moveend”, function(){

alert(map.getCenter())

}

)

}

}

The getCenter() method of the GMap2 returns the current focus latitude and longitude of the map. That’s all for this quickie.

The Hello World experiment has impressed upon me the ease of setting up Google Maps for a website. However, it had only limited functionality. Also I wanted to check how it works with ‘conventional’ JavaScript APIs. The best way is to cook-up some animation (eventhough it may not mean much). So when I saw a function to change the focus of the area displayed, I thought let me create an animation with it. In JavaScript, there are two kinds of timers available –

1. One that executes a given function exactly once after a specified amount of delay

2. Another that executes the function repeatedly after a specified interval.

The corresponding functions are:

1. setTimeout and

2. setInterval

respectively. Both are the methods of window object. So now how to use it to animate google map. For that the API I am going to use is:

panTo:

This is a method of GMap2. What it does is it changes the center of the map to the given point represented by latitude and longitude.

So how to use this to achieve animation? The methods are as follows:

1. By using setTimout with panTo:

Adding the setTimeout just after setting the focus point of map, would create a one shot animation. That means it would be panned only once. The code would look like :

function load() {

if (GBrowserIsCompatible()) {

var map = new GMap2(document.getElementById(“map”));

//map.setMapType(GMapType.G_HYBRID_MAP);

map.addControl(new GSmallMapControl());

map.addControl(new GMapTypeControl());

map.addControl(new GScaleControl());

map.setCenter(new GLatLng(31.122027, 77.111664), 13);

window.setTimeout(function() {

map.panTo(new GLatLng(31.152027, 77.111664));

},18000

);

}

}

the setTimeout is given an anonymous function as the function to be called and nearly 15 sec as the time to wait before function is executed.

2. By using SetInterval with panTo:

This comes handy when u want to the focus return to a particular point again and again after a specified time interval. The syntax is similar to that of setTimeout. The only difference is in the way both functions. Following is the same code implemented with setInterval:

function load() {

if (GBrowserIsCompatible()) {

var map = new GMap2(document.getElementById(“map”));

//map.setMapType(GMapType.G_HYBRID_MAP);

map.addControl(new GSmallMapControl());

map.addControl(new GMapTypeControl());

map.addControl(new GScaleControl());

map.setCenter(new GLatLng(31.122027, 77.111664), 13);

window.setInterval(function() {

map.panTo(new GLatLng(31.152027, 77.111664));

},18000

);

}

}

That’s it for this post. By the next post I would have experimented the event handling provided by GMap API.

.

A quick update. One of the most important and the thing of frustration for anyone starting with GMap API is getting hold of desired latitude and longitude. There are many ways. I am listing here one of the easiest ways to get the latitude and longitude of desired location. Here are the steps:

  1. Go to the following site : http://www.infosports.com/m/map.htm
  2. Navigate the map till you get the desired location. For example, I required the lat and long. of Shimla. So I navigated (panned and zoomed) till I got to Shimla.
  3. Then click on the spot. In my case its Shimla. A marker would be generated at that point.
  4. click on the marker to get the latitude and the longitude. Mine is 77.16496467590332, 31.102995000257405

That’s it. If there are easier ways do share.

.

In the last post I had said I wanted to add something extra to the Hello world of GMap. The extras are controls. So the second part is:

2. Adding Controls to the map:

The map looks plain without the controls for scaling and mapping. So I decided to jazz it up with the following controls:

i. GSmallMapControl:

It shows a control with four buttons to pan(move the map) in four directions alongwith buttons to zoom in and out. The constructor is GSmallMapControl().

ii. GMapTypeControl:

It provides the control to change the type of map. The types are map, satellite image and hybrid which shows map superimposed on satellite image. GMapTypeControl() is the constructor.

iii. GScaleControl:

As the name suggests, it shows a scale within the map.

So how to add them to the map? The way is pretty simple- use the addControl() method of GMap2 instance. Here is the way in code:

function load() {

if (GBrowserIsCompatible()) {

var map = new GMap2(document.getElementById(“map”));

//add the controls to the map

map.addControl(new GSmallMapControl());

map.addControl(new GMapTypeControl());

map.setCenter(new GLatLng(31.122027, 77.111664), 13);

map.addControl(new GScaleControl());

}

}

If you have observed, there is a difference in adding GScaleControl when compared to others. The first two controls (for that most of the controls that I have tested) are added before setting the center of the map where as the GScaleControl() is set after the center of the map has been set. What would have happened if I had called it before setting the center? The result would have been a blank page with a JavaScript error. That’s what happened with me. If you get any different result please share.

That’s it for this post. Next I would be looking at event handling in Google Map.

Last week I had said that I would be cooking up a “Hello World” kind of app. I did it. There were two parts:

  1. Display default location provided by GMap API:

In nutshell, just make the sample app provided by Google while registration, work on my local system. It also clarified one of my doubts – where is the API library of GMap located? ‘Coz it was not provided when I registered. For some, it may be a silly question. Ok. So the answer is in the following line:

<script src=http://maps.google.com/maps?file=api&v=2&key=[yourkey]“

type=”text/javascript”></script>

The src attribute is pointing to the place where APIs are available. The place is maps.google.com – the site of Google maps. Along with the URL key received while registering with Google maps. Next comes the implementation of custom logic. It starts with the function load():

<script type=”text/javascript”>

//<![CDATA[

function load() {

}

//]]>

</script>

The next step is to ensure browser compatibility with client browser. This is done using GBrowserIsCompatible().

<script type=”text/javascript”>

//<![CDATA[

function load() {

if (GBrowserIsCompatible()) {

}

}

//]]>

</script>

Once compatible browser is found, then an instance of GMap2 class is created. The parameter passed id the div object in which the map has to be shown:

<script type=”text/javascript”>

//<![CDATA[

function load() {

if (GBrowserIsCompatible()) {

var map = new GMap2(document.getElementById("map"));

}

}

//]]>

</script>

The last step is to display the map using setCenter() method of GMap2. the method takes latitude , longitude and zoom factor as parameters. Of these zoom is optional.

<script type=”text/javascript”>

//<![CDATA[

function load() {

if (GBrowserIsCompatible()) {

var map = new GMap2(document.getElementById("map"));

map.setCenter(new GLatLng(31.122027, 77.111664), 13);

}

}

//]]>

</script>

The last but not least is the HTML especially the div part:

<body onload=”load()” onunload=”GUnload()”>

<div id=”map” style=”width: 500px; height: 500px”></div>

</body>

The load() has to be called in body’s onLoad is obvious. Calling GUnload() is a good practice to avoid memory leaks. That’s for the first part.

I started my exploration of Google Map API. For those who came late, Google Map API provide way to harness the power of Google Maps for your site. The API itself is JavaScript based. So if you have intermediate knowledge of JavaScript, then you are ready to work with GMap API.

The first step is to get a registration key. The key is a string which GMap server uses to ‘recognize’ and authenticate you. To get the key the registration page asks for your web-site address. If you already have a website, then everything is well and dandy. However what if you are like me (I still dont have a page of my own)? My first thought was to grab a free web host such as geo-cities. But then decided to check the tried and tested ‘localhost’. I was not sure about Google accepting it. I was in for a surprise. It accepted the URL http://localhost readily and provided me the key. And thus I was well and ready to do my exploration and experimentation with GMap API.

Next step is to test the API with GMap’s version of Hello World. That I will be doing tonite. More about it tomorrow.

Follow

Get every new post delivered to your Inbox.