Google Maps API – introduction

This is translation of my HOWTO written in Polish. Information here was accurate as for 20.08.2007, with Google Maps API in version 2.73 (stable). However it seems still proper as for April 2008)

Do You need get Google Maps API application up and running in short time with some advanced features? Drop me a line, I do write such applications.

Google Maps API – introduction

First You need to get Google Maps API key, to run application on Internet. If You wan to play with API on Your computer, as long as You use localhost as an address API key is not needed. To get one visit: http://www.google.com/apis/maps/signup.html

Warning!
Read carefully terms of service, there are some restrictions (like number of geocoding requests or public access to Your map application). If there are some limitations which does matter for You, it is possible to obtain enterprise license without such restrictions.

Hello world!

Basically applications which want to use Google Maps API need to include JavaScript file from Google servers. This file contains code with library to create and operate on map on Your page. API key is way how Google identifies Your application, and You have to run this application on URL similar to one used when You have requested API key.

There is one exception – localhost, on which You can run application without any key.

With API key we can start. So, for a start, we have to create some div object:

 
<!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>
    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    <title>GM API: hello world</title>
    <script src="http://maps.google.com/maps?file=api&v=2.s&key=API_KEY"
    type="text/javascript"></script>
    <script type="text/javascript">
     //<![CDATA[
     function load() {
       if (GBrowserIsCompatible()) {
         var map = new GMap2(document.getElementById("map"));
         map.setCenter(new GLatLng(52.23185395123989, 21.02083683013916), 17);
       }
     }
     //]]>
     </script>
   </head>
   <body onload="load()" onunload="GUnload()">
     <div id="map" style="width: 600px; height: 400px"></div>
   </body>
 </html>

Full example here

Our Hello world displays map of center Warsaw, You can scroll map through dragging. Now few word of explanation:

In line 7 You should replace API_KEY with real API key, You got from Google. In line 13 the actual object representing map gets created. To constructor method pass id of DOM object, which will be holding map. It has to be element div with two CSS properties set width and height (line 21).

In line 14 map is initialized, when setCenter is called. This is required before You call any other method on map object.

Other important thing to remember is to call GUnload when page is destroyed (You can do it with onunload property of body – line 20). This should minimize chances for memory leaks.

Basic controls

Now we will allow users for some more interactions with our map. To allow for some basic operations on zoom we need to add few calls to load function:

 
map.addControl(new GLargeMapControl());
map.addControl(new GMapTypeControl());
map.addControl(new GScaleControl());

Now we have control over over zoom (GLargeMapControl), view type (map/satellite) (GMapTypeControl) and some scale information (GScaleControl).

Map with this controls becomes a bit more useful, but still it does only present data fetched from Google.

Map with controls is available here

Where am I? or how to search for address

When You need to find some particular place dragging map with mouse, it works well if You know exactly where looking place is and it is not far from current viewport. In other cases – geocoding for help. Geocoding is name for finding coordinates for given address.

With Googl Maps API You can do it with GClientGeocoder. After You initialize it, You can call getLatLng method passing two arguments. String with address and function which expects one argument (type GLatLng). After geocoding this function will be called with point representing address or it will be undefined if Google Maps API couldn’t find this address. First we create geocoder:

var geocoder = new GClientGeocoder();

next we associate findAddress function with some HTML form:

 
<form action="#" onsubmit="findAddress(this.address.value); return false">
<p>
<input type="text" size="60" name="address"/>
<input type="submit" value="Go!" />
</p>
</form>

After user pushes Go! content of text field will be passed to findAddress. Let’s examine this function:

 
function findAddress(address) {
       geocoder.getLatLng(
         address,
         function(pt) {
           if (!pt) {
             alert(address + " - can not find");
           } else {
             map.setCenter(pt, 13);
           }
         }
       );
    }

Code is available here

In line 26 we are using variable initialized in line 12, pass address and closure which will called with result of geocoding. By default geocoding requests are asynchornous. That means Your application won’t stop waiting for results of getLatLng call. It prevents browser from being frozen, but it has some side effects.

After call to getLatLng, browser will interpret next line of JavaScript code (in this example it will be line 36, function end). It can lead to some problems. This example uses static HTML but probably You will use some server side backend. Right now all communication (geocoding) is between client browser and Google servers. You may want to inform own server, that user was looking for some address, and probably display some new data on map according to new view port. It seams natural to use AJAX call to inform our application about current map center. We may come to code similar to this (using Prototype to handle AJAX):

 
     function findAddress(address) {
       geocoder.getLatLng(
         address,
         function(pt) {
           if (!pt) {
             alert(address + " - can not find");
           } else {
             map.setCenter(pt, 13);
           }
         }
       );
       new Ajax.Request('/app/hey_map_got_new_center, 
          {method: 'post', postBody: 'center='+map.getCenter().toUrlValue() }
 }

It won’t work. And not only because of not existing server side code. Here is how execution will flow in most cases:

  • line 26 – asynchronous call to geocoder
  • line 36 – Ajax.Request with old value returned by map.getCenter()
  • return from closure
  • After geocoding process was finished by Google and was returned to browser, new map center will be set with setCenter call in line 32 (if address was recognized at all)

So You should move Ajax.Request call to closure in findAddress function (between lines 32 and 33). That way we can be assured AJAX call will use new and right coordinates.

Placing markers on map

With Google Maps API You can mark places on map with markers (have You seen that coming? :) ). API uses GMarker for representing such objects. For constructor You have pass at least coordinates as GLatLng object. This is enough to know for start, so let’s do it!

 
         map.addOverlay( new GMarker( new GLatLng( 52.23185395123989, 21.02083683013916) ) )

Example here

Code above will show some object, very specific for Warsaw. Switch to hybrid view, and in case You don’t know what it is try this query.

Starting from now Google Maps API takes car about displaying (or not) marker, depending on current map center and zoom level. Markers is one of overlays available. Other can be lines and polygons.

Mum! Can I draw something on a wall in the living room?

Lines are represented with GPolyline. Simple pass array with GLatLng objects to get line drawn according those points. If we want to show how to see tree from earlier example from each side, we could use following code:

 
         points = [
           new GLatLng (52.23212993512015, 21.020729541778564),
           new GLatLng (52.231913090787245, 21.020150184631348),
           new GLatLng (52.23143340107545, 21.020429134368896),
           new GLatLng (52.23158453674942, 21.02134108543396),
           new GLatLng (52.2321430771669, 21.021265983581543),
           new GLatLng (52.2321430771669, 21.020890474319458)
         ]

         map.addOverlay ( new GPolyline (points) )

Watch it here

I wrote a tool for gathering data to draw such lines/polygons Check http://nhw.pl/download/points.html. It will help You.

To properly draw lines we need to tinker with HTML in few places. First line 3 gets this form:

 
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml">

And we have to add special CSS rule:

 
      38   <style type="text/css">
      39   v\:* {
      40     behavior:url(#default#VML);
      41   }
      42   </style>

This is caused by Internet Explorer. With this browser lines are drawn as VML (Vector Markup Language). Without those changes lines won’t be visible with IE. So if IE does not want to draw lines from Your application make sure You have applied those changes.

Markers are not very verbose, so we need to place additional description. With openInfoWindowHtml method for some marker we can add HTML description, which can be displayed after marker was clicked. After we create marker we have to register handler for click event:

 
         map.addOverlay( marker = new GMarker( new GLatLng( 52.23185395123989, 21.02083683013916) ) )

         GEvent.addListener(marker, "click", function() {
               marker.openInfoWindowHtml("Don't You know what is here? Find it out "+
               "<a href='http://images.google.com/images?hl=en&q=palma+warszawa&btnG=Search+Images&gbv=2'>"+
               "here</a>")
            });
 

Whole example here

Remeber: placing images in info window You have to provide theirs width and height. If You skip this, info window can be to small and images will be partially outside of window. Does not look like professional work ;) so watch out ;)

This example also have shown how Google Maps works with events. Custom handlers for such events allow build really interactive application. API generates events for many user actions making it possible to react to those user actions (like click, drag, double click and many other).

To react on events we need to tell API which one are interesting to us and delegate code to serve this purpose. With Google Maps API we have namespace GEvent. addListener is function which is interesting to us right now. This is why we have used GEvent.addListener in line 24, which have registered our handler for event click for GMarker we have created earlier.

More documentation and examples

Here I have presented some really basic informations, on the net there is plenty resources for anybody interested in Google Maps API. First – Google has high quality documentation available under http://www.google.com/apis/maps/documentation/. Very useful information source is http://groups.google.com/group/Google-Maps-API/.

From other sources I recommend You Mike William’s page devoted Google Maps API (Mike is also very active member of Google Maps group) http://www.econym.demon.co.uk/googlemaps/.

Quite good information source is Mapki


Do You need application using Google Maps API? Or just Ruby on Rails web application? Drop me a line, I do such projects.


(c) Witold Rugowski
ver 1.1 2007.08.24

3 thoughts on “Google Maps API – introduction

  1. My replay on:introduction-to-google-maps-api

    thnx for info.
    It’s allot like the google docs but easier to read for a GMaps noob like me.

    Bastiaan (Netherlands)

  2. Pingback: VolksMate's googlemap Bookmarks on Delicious

Leave a Reply

Your email address will not be published. Required fields are marked *