Looking for a quick and easy way to add a little eye candy to your website? Look no further than Google Maps. Developers comfortable working with basic JavaScript will have no trouble using Google Maps to visualize their geospatial data.
Geospatial Data - information that relates to a geographic location. For example, a street address such as:
11700 Plaza America Drive
Reston, VA 20190
Let's get started! Follow these simple steps you'll be up and running with Google Maps in no time:
1. Sign Up for a Google Maps API Key
If you want to use Google Maps you will need an API key. Sign up is painless. Just access the following URL and follow the sign up steps:
http://code.google.com/apis/maps/signup.html
The API key is free, but you will need to create a Google account if you don't already have one.
If you are just going to experiment with Google Maps on your local desktop computer or laptop just enter "http://localhost" in the "My web site URL" field.
2. Include the Google Maps JavaScript API
Include the following JavaScript in your HTML <head> element:
<script type="text/javascript"
src="http://maps.google.com/maps?file=api&v=2&key=
YOUR_GOOGLE_MAP_API_KEY_HERE">
</script>
This will import the Google Maps JavaScript API into your webpage. Be sure to replace the "YOUR_GOOGLE_MAP_API_KEY_HERE" text with the key you generated in the previous step.
3. Check Browser Compatibility
We will need to create a JavaScript function that will be called when our page initially loads. This function will be used to call into Google's Map API and load the map onto our webpage. We'll call this function load() and I'll break it down for you over the next few steps.
The first thing we'll need to do in our load() function is check to make sure that the browser we are using is compatible with Google Maps by calling the GBrowserIsCompatible() function provided by the API:
function load() {
if (GBrowserIsCompatible()) {
...
}
}
Most major browsers are supported so this shouldn't be much of an issue, but you may want to display a message to your users if their browser is unable to load the map.
4. Create a New Map Object
map = new GMap2(document.getElementById("mapDiv"));
The document.getElementById("mapDiv") tells Google Maps where to place the map in our HTML. In this case, we'll place it inside of a div with the id "mapDiv".
5. Set the Center of the Map
Google Maps will want to know where to center the map on your screen and you can tell it by calling the setCenter function on the map object created in Step 4.
map.setCenter(new GLatLng(39.978030, -95.295274), 4);
The first parameter is a latitude and longitude point of White Cloud, Kansas. I used this particular point because it's more or less in the middle of the United States and that's where I wanted my map to be centered.
The second parameter "4" is the zoom level of the map. Zoom levels range from 0 (All the way zoomed out) to 17 (All the way zoomed in).
6. Create a New Geocoder
geocoder = new GClientGeocoder();
Simple Enough. I'll explain what a geocoder is and what it does in Step 8.
7. Create an Array with Geospatial Data (Addresses)
There are a variety of ways in which geospatial data can be sent to the Google Maps API so the example included in this step should only act as a guide to help you understand one approach that can be used to plot data on a map.
For this example let's pretend that we want to plot the locations of our favorite water parks across the country. We want to create an array of these water parks and then pass them off to Google one at a time to be placed on our map. The code for this scenario would look like this:
//Multi-dimensional array storing:
//[['Water Park Name','Water Park Address']]
//Truncated to save space ...
var waterParks = [];
waterParks.push(['Great Wolf Lodge','549 East ...']);
waterParks.push(['Mountain Creek Waterpark','2...']);
waterParks.push(['Aquaport','2344 McKelvey Rd ...']);
waterParks.push(['Knott\'s Soak City','1500 S G...']);
waterParks.push(['Adventure Landing','1944 Bea...']);
if (geocoder) {
for (var i = 0; i < waterParks.length; i++) {
plotAddress(waterParks[i]);
}
}
Basically we have created a multidimensional array that stores the water park's name and its associated address.
Once we have our array we can loop through it and send each individual array element to the plotAddress() function. This function was created for the purpose of this example and is not part of the Google Maps API. The plotAddress() function is explained in the following step.
8. Plot the Markers on the Map
I mentioned in the previous step that I created a function called plotAddress() to place the water park locations on the map. Let's take a look at this function and break it down for clarification:
function plotAddress(waterPark) {
//waterPark[1] = water park address
geocoder.getLatLng(waterPark[1], function(point) {
if (point) {
var marker = new GMarker(point);
GEvent.addListener(marker, "click", function() {
//waterPark[0] = water park name
marker.openInfoWindowHtml('<h2>'+waterPark[0]+'</h2>');
});
map.addOverlay(marker);
}
});
}
Before we can plot the water parks onto a map, their addresses will first need to be converted into latitude and longitude coordinates. Remember that in Step 6 we used the Google Maps API to create a geocoder.
Geocoder - a geocoder is used to translate a human readable address into its corresponding latitude and longitude coordinates which can then be used to plot items onto a map.
For example:
11700 Plaza America Drive
Reston, VA 20190
Latitude: 38.953267; Longitude: -77.349951
Notice that we send the geocoder.getLatLng() function 2 parameters. The first is the address of the water park and the second is a call back function based on the "point" (latitude/longitude) returned after geocoding the address.
If a point is successfully returned then we create a "marker" (an icon to be placed on the map) with that point's value.
Optional: To spice things up a little bit we also add an event listener to the marker so that whenever it is clicked the name of the water park will appear in a speech bubble above it.
Finally, we add the marker overlay to the map. This step takes the marker and places it onto the map on our webpage.
9. Add a Map Control
Once we return from looping through the water park array and placing the items on the map we will want to add a map control:
map.addControl(new GLargeMapControl());
This step is also optional, but highly recommended as it will give your users the ability to zoom in and out and pan across your map.
10. Add the HTML
The last step is simply to add the HTML to your page where the map will live:
<body onload="load();" onunload="GUnload();">
<div id="mapDiv" style="height: 350px; width: 700px;">
</div>
</body>
Remember in Step 4 when created a new map object with the div id "mapDiv"? We can clearly see that this div is created in the HTML above.
Also notice that when the page is loaded we are calling the onload="load();" JavaScript command to run our load() function. It's also important to call Google's GUnload() function on page unload to clean up the map resources used by your webpage.
Putting it all Together
Once you put everything together you should be able to load the map into your browser and receive results similar to the following screenshot:
Wrap Up and Resources
There are a couple of "gotchas" associated with the Google Maps API:
- Geocoding addresses is slow and can affect the performance of your webpage.
- There is a limit of 15,000 geocode requests per day. This may seem like a lot, but if you have a site with any significant amount of traffic, this number is well within reach.
- If you try to geocode to many addresses at once, Google Maps can potentially error out and provide incomplete results on your map.
To overcome some of these gotchas, check out my blog post: Geocoding Made Easy with Groovy and Google.
We've really only scratched the surface with this brief introduction to Google Maps so be sure to checkout the following pages for more information:
Google Maps Documentation
Google Maps Examples
Google Maps Reference Manual
Click here to download the source used in this example and try it out for yourself.

Comments
Post new comment