If you're new here, you may want to subscribe to my RSS feed. So that you can read the latest updates about Web2.0 tools, Making Money Online, Tips in SEO, Ajax and many more. Thanks for visiting ProgramimiCOM!

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 — for example, for tracking reports of shipments. However even two years ago, embedding a map within an application was a specialized area that required a good understanding of Geographical Information Systems (GIS). This changed with the arrival of Google Maps and its corresponding set of APIs, known as the Google Maps API.

Now a developer with a good grasp of JavaScript can without much ado embed an interactive map in a web application using the Google Map API. The questions that arise next are what exactly is the Google Map API and what are the steps one needs to follow in using it. The answers to these questions is the focus of this discussion.

In the first two sections of this article I will deal with the whys and wherefores of the Google Maps API. In the third section I will detail the steps you need to take when using the Google Maps API. The last section will focus on a real world example based on the steps discussed in third section. That is the outline of the discussion.

What is the Google Maps API?

Google Maps 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 and so forth. Google Maps API provides an interface into these operation through JavaScript objects. The beauty of the setup is that the functions work in the same non-intrusive way as the original Google Maps without the developer needing to know the details of AJAX or how it is implemented in Google Maps. The developer only needs to know the classes and their methods to access the services of Google Maps. The functions exposed by the Google Maps 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 access to most of the group of functions mentioned above is through the methods of the GMap2 class. The GMap2 class forms the basis of map creation, display and manipulation.

Configuration

All of the aspects of any map provided by Google Maps are configurable, whether it’s the enabling of dragging and information windows or continuous zooming. The methods of the GMap2 class sectioned under configuration enable configuration of the map. The following are the most often used methods for configuring maps:

  • enableDragging() enables the dragging of the map. Dragging is enabled by default.

  • disableDragging() disables the dragging of the map.

  • enableInfoWindow() enables the information window.

  • disableInfoWindow() disables the displaying of the information window.

Controls

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

  • addControl(control, [position]) adds the specified control to the map at the place specified by the position parent. The position parameter is optional.

  • removeControl(control) removes the specified control from the map.

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

More Google Maps API Functions

Map Types

Google Maps provides three types of map: a simple map that provides an outline-based map, a satellite map that streams the satellite-imaged maps and a hybrid map which combines both of the aforementioned maps. The map types provided by Google Maps are controlled by the following methods:

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

  • removeMapType(type) removes a map type that has already been set.

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

Map State

The methods that provide information about the state of the map come under this heading. The information provided by map state methods include whether the map is loaded or not, the current focus point or center of the map, and more. The commonly used methods are:

  • isLoaded() tells whether or not the map is loaded onto the client browser.

  • getCenter() provides the latitude and longitude of the center of the current view port of the map.

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 the rest of the map. The most used methods in this category are:

  • addOverlay(overlay) adds an overlay presented by the overlay object passed as a parameter.

  • removeOverlay(overlay) removes an overlay already added and represented by the overlay object passed as a parameter.

The overlay object can be of the GPoint or GPolyline types.

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. The following are the main methods used to control an info window:

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

  • showMapBlowup(latlng,[opts]) opens an info window at the specified latlng containing the close-up view of the latlng specified as a parameter.

The parameter latlng is of the GLatLng type.

Map Navigation

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

  • setCenter(center,[zoom],[type]) loads the map focused on the point specified by center with an optional level of zoom and type of map.

  • panTo(center) navigates to the point on the map specified by center.

  • setZoom(level) zooms into or magnifies the current center to the level specified with the parameter level.

Events

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

  • click is generated when the user clicks on any point within the boundaries of the map.

  • move is fired when the map is moving or panning. During panning it may be fired many times.

  • moveend is fired when the panning is completed.

That brings us to the end of the first part of our discussion. In the next section I will detail the steps required to work with the Google Maps API.

Using the Google Maps API, Step By Step

Now that the services provided by the Google Maps API have been discussed, let’s see what steps we need to take to use the API. To use the Google Maps API, two main steps have to be followed:  acquiring the registration key and setting up the map. The second step consists of sub-steps that actually deal with the setting up of HTML and the Google Maps API library.

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. the 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 along with an example will be provided which can be used as a base for further developments.

Setting up the map

The Google Maps API library is a JavaScript library. So its focus includes HTML and JavaScript based applications. In other words, the Google Maps API targets the UI for the web applications. To set up the page to display the map the required steps include setting up the HTML page and importing/including the Google Maps API.

Setting up the HTML page

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

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

Importing/Including the Google Maps API

To use the API, its library has to be referenced. In the case of JavaScript, importing or including the library (which are just other terms for referencing a library) is done using the src attribute of <script> tag. So to include the Google Maps 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 the src attribute tells us two important points about the Google Maps API. The first is the location of the API which is Google’s site itself. So even for testing purposes, availability of the Internet is required. The second is the 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 an authorized site.

The next step is to implement a function that will 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. It would be called from the body thus:

<body onload=”load()” >
:
:
</body>

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

if (GBrowserIsCompatible()) {
  //…
}

To display the map what we need is an object of the GMap2 class. To get it, we’re required to use the GMap2 constructor with the id of the <div> serving as a placeholder. For example the following code creates an instance of the 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 the map variable. The argument passed is of the GLatLng type 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 the map by using the methods enumerated in the first section. The last but not least point is to call GUnload() through the onunload handler of the body tag to prevent memory leak:

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

That brings us to the end of the third section. In the next section I will develop a small application that will show the different functions discussed in the first two sections and use the steps detailed in this section.

The Google Maps API in the Real World 

Now I will build a small application that displays a map using the Google Maps API. It does the following:

  1. Displays the map with Shimla (India) as its center.
  2. Provides zoom and pan controls for navigation.
  3. Provides a map type control to change between the three map types.
  4. Handles the click event and display information window showing the current focus point upon a click on the map.

So let’s 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() {
}
</script>
</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 the Google Maps API and declares the load function. Next comes 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);
}

          }
</script>
 

</head>
<body onload=”load()” onunload=”GUnload()”>
<div id=”map” style=”width: 500px; height: 500px”></div>
</body>
</html>

Next we 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);
}
}
</script>

</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 an 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 a few lines it does a lot. This was just a teaser of what the Google Maps API can do. In future articles I will discuss advanced features such as communicating with servers and geo-encoding. Till then….

by A.P.Rajshekhar