I have been toying with Google maps for a week or so now and have found them tricky if you don’t immediately understand what the hell is going on.

First things first, you need to register an API key (here) so that you can send requests off to their server and get a response that doesn’t read something like ‘Invalid API Key’. Google map API keys are domain specific but you can always register localhost or your internal domain ip which will still work.

The most logical thing to want to do when you have the key is display a map (Really?). Google offer a nice piece of JS to get you started so ill start with that:

<!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>Google Maps JavaScript API Example</title>
    <script src="http://maps.google.com/maps?file=api&v=2&key=##YOUR-KEY-HERE##"
      type="text/javascript"></script>
    <script type="text/javascript">

    //<![CDATA[

    function load() {
      if (GBrowserIsCompatible()) {
        var map = new GMap2(document.getElementById("map"));
        map.setCenter(new GLatLng(37.4419, -122.1419), 13);
      }
    }

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

Simple eh? of course this code is great if you only ever want one map per page in a div called ‘map’ but this isn’t really very dynamic now is it. Once you get it running you’ll find out its just displaying a map of google headquarters somewhere in america with no map controls or anything useful (unless of course you wanted to know where google headquarters was).

So… to make this map usable we can do a number of things:

  1. Make the div name dynamic
  2. De-fluff the code and put it into a php template
  3. Sort out the &’s in their script call
  4. Pass the coordinates as a function argument to make it easier to use usable

Following my above points we are left with the following:

<?php
class map_test {
	function __construct($google_api_key) {
		$js = "<script src=\"http://maps.google.com/maps?file=api&v=2&key=" . $google_api_key . "\" />";
		$js .= "<script type=\"text/javascript\">
		function load() {
			if (GBrowserIsCompatible(mapName, latitude, longitude)) {
				var map = new GMap2(document.getElementById(\"mapName\"));
				map.setCenter(new GLatLng(latitude, longitude), 13);
			}
		}
    		</script>";
		echo $js;
	}
	function render_map($latitude, $longitude) {
		$div_id = 'map' . mt_rand(1000,9999);
		$html = "<div id=\"" . $div_id . "\" style=\"width: 500px; height: 300px\"></div>";
		$html .= "	<script>
					load(" . $div_id . ", " . $latitude . ", " . $longitude . ");
				</script>";
		echo $html;
	}
}
$google_api_key = "##YOUR-KEY-HERE##";
$latitude = 37.4419;
$longitude = -122.1419;
$map = new map_test($google_api_key);
$map->render_map($latitude, $longitude);
?>

Ok, so what we have here is just a longer way of rendering to the screen yet another map of Google’s headquarters. Look a little closer at the code and you will see that I have extracted the hard coded parts of the JS into variables that something like PHP can manipulate to display a map of pretty much anywhere you want to see. Just change the API key to yours and toy with the coordinates to see a map of anywhere you like.

The render_map function can be called as many times as you like, each time displaying another map of the coordinates you pass it.

The next logical addition to this script is to add controls for zoom and pan. These are surprisingly easy to integrate. Simply add the following lines to the JS ‘load’ function just after the line that defines the new GMap2:

map.addControl(new GSmallMapControl());
map.addControl(new GMapTypeControl());

These will work assuming of course that you haven’t renamed the ‘map’ variable.

Next you will probably want to add a marker (for Google headquarters) to show the thing you are looking at in more detail. These are done in the form of those pushpin things you usually see or as Google calls them, ‘markers’. The followng JS function will add a marker at the coordinates passed:

function addMarker(map, latitude, longitude, description) {
    var point = new GLatLng(latitude, longitude);
    var marker = new GMarker(point);
    if (description.length > 0) {
        GEvent.addListener(marker, "click", function() {
            marker.openInfoWindowHtml(description);
        });
    }
    map.addOverlay(marker);
}

You may want to put your JS code into a .js file and store it appropriately at this point because really large functions written in different languages can be confusing… Either way, put the above code below your ‘load’ function and call it using this line:

addMarker(map, latitude, longitude, desc);

Simple enough to understand really but it passes the map object we created earlier, the longitude, latitude and a description to the function to add a marker. If you don’t want a description for the marker then just pass an empty string or null.

You now know how to show visitors to your site where google headquarters is. Handy I know! See my future post for ‘Geocoding’ an address to get those all important coordinates for any location on the globe onto a google map.

Sean

For more Google map API help, who better than to ask than Google themselves: API Page

A donate button!

Be the first to hear about new products/updates!

This is a mailing list for those people interested in being told when we release a new product (Divi plugin or Theme).

We shall also use this list to let you know about product updates and releases.

You have Successfully Subscribed!