Friday, February 24, 2012

Google Maps API Part 1 Introduction

I spent some time over the past few days looking at Google's Maps API because I wondered how those site like ridewithgps, mapmyride, and gpsies worked. If any of you are semi-skilled javascript coders you'll be impressed at how easy it is to use.

Here's a simple tutorial showing how to display a map of Yorba Linda Regional Park, display the latitude and longitude at the cursor location, and reverse geocode (get nearest address) when the user clicks the mouse. It's designed for IE8.

Start by declaring the document as HTML5 and add the default html, head, and body tags. The style attributes are required because IE won't resize the body automatically when the map is rendered.
<!DOCTYPE html>
<html style="height:100%">
    <head>
    </head>
    <body style="height:100%">
    </body>
</html>

Now add the DIV that will host the map into the body. Do not use the shorthand "/>" because of a bug in IE8. Note that when you bind a Google Maps mapping or visualization object to an HTML element all the child nodes of the element are deleted.
<div id="map_canvas" style="width:100%; height:100%"></div>

Add the references to Google's mapping API. We are only using basic functions so we only need the basic library. Extended functionality like charting is available through other libraries. The example below goes into the head and makes anonymous requests to Google's servers. If you have a gmail account you can get a key which you pass by adding a key=xxxxxx parameter. The key lets you make more requests and also track your usage.
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>

Now let's display a map of the Yorba Linda regional park. The simplest way to do this is with latitude and longitude. To do this we create a function called initialize which defines a dictionary of map options and then creates the map using the hosting DIV and the map options. This script goes immediately after the script tag above.
<script type="text/javascript">
function initialize()
{ var mapOptions = {center:new google.maps.LatLng(33.86, -117.76),
            zoom: 14,
            mapTypeId: google.maps.MapTypeId.ROADMAP}
  var divCanvas = document.getElementById("map_canvas");
  map = new google.maps.Map(divCanvas, mapOptions);
}
</script>

Now all we have to do is call initialize once the page has loaded. Add an attribute to the body tag so it looks like this.
<body style="height:100%" onload="initialize()">

You can now run the page. You will see a Google Map of Yorba Linda which you can pan, zoom, change layers, even go to street level. Not bad for a little javascript. Let's add an event handler now so we can see the latitude and longitude at the mouse location.

Add the following line of code as the last line in the initialize function. It tells the map object to call a new function called showlatlong whenever the mouse moves over the map.
google.maps.event.addListener(map, "mousemove", showlatlong);

Add the following function after the initialize function. It will be our mousemove event handler. Note that all event handlers receive an event argument.
function showlatlong(event) {
  var latitude = Math.round(event.latLng.lat() * 10000) / 10000;
  var longitude = Math.round(event.latLng.lng() * 10000) / 10000;
  window.status= 'Lat: ' + latitude + ', Long: ' + longitude;
}

Now run the mouse over the page again and note that the longitude and latitude are displayed in the window's status bar. The last thing I'll cover is reverse Geocoding which determines the nearest street address to a latitude/longitude. It is an asynchronous call which is common in Google Maps. This means we have to assign a callback function that is called when the results are available.

We start by declaring a geocoding object. Add the following line of code before the initialize function.
var geocoder=new google.maps.Geocoder();

Now we add a new event handler as the last line of the initialize function.
google.maps.event.addListener(map, "click", showaddress);

Because reverse geocaching is asynchronous all we do in the event handler is make a request to Google Maps and tell it where to send the results. The geocode method takes a dictionary of options just like the map method.
function showaddress(event) {
  geocoder.geocode({ 'latLng': event.latLng }, showGeocodeResults);
}

All Google Maps callbacks receive a results object and a status string. The geocode results are an array of address objects. The first address is the most specific but may not be populated (if you clicked on the North Pole you may not get a street address). We iterate through the array until we find an entry with a populated address property.
function showGeocodeResults(results, status)
{ if (status == google.maps.GeocoderStatus.OK)
  { for (var i = 0; i < results.length; i++)
    { if (results[i].formatted_address != undefined)
      { window.status = results[i].formatted_address;
        return;
      }
    }
  }
}

Try running the page again and click on the map. You will see the nearest mailing address displayed in the window's status bar. Because this is an asynchronous call there will be a slight pause before the result comes back.

There are some good tutorials at http://code.google.com/apis/maps/documentation/javascript/tutorial.html

No comments:

Post a Comment