Wednesday, June 29, 2005

using Google Maps API in Blogger

Google Maps has released a public API, making it easier to incorporate maps into your own webpage. Like so, hopefully:


You'll need to sign up for a key that is specific to your website; they don't even ask for an email address, just the URL you intend to use the API on.

Adding a map to a page is pretty simple:
  1. Add Google's script to your page
  2. Add an empty DIV to the body of your post where you want the map to be
  3. Add scripting to target that empty DIV by id

In addition to this there are two requirements that are specific to posting on Blogger:
  1. Blogger kicks up an error when you try to submit a post that has <script> tags in it. Underneath the error is a checkbox that says "Stop showing errors for this post"... click that and resubmit, and the post goes through fine.
  2. If you have Settings... Formatting... Convert line breaks set to 'yes', you need to make sure the entire script is on one line... <br /> tags in the middle of a script usually cause the script to fail.

There is a final caveat that applies to using Google Maps on any blogging system:
  1. When you assign an ID to the blank target div, make it unique and make sure that the accompanying script targets that unique name. On this page instead of using the ID 'map', I used 'map062905' because I probably won't put up another map today, but if I put up another one tomorrow I don't want the scripts to be confused. Each map needs a unique ID.


If you can see a map above, the code looks like this (line breaks and comments have been added for clarity):

<head> tag:

<script src="http://maps.google.com/maps?file=api&v=1&key=my_key" type="text/javascript">
</script>

Post body:

// empty DIV with unique ID, styled to your liking
<div id="map062905" style="width: 300px; height: 300px; margin: 0 auto;"></div>

// script that calls the API
<script type="text/javascript">
// associate a new map object with the empty div
var map = new GMap(document.getElementById("map062905"));
// add size/pan controls
map.addControl(new GSmallMapControl());
// add map/satellite controls
map.addControl(new GMapTypeControl());
// center the map on your target and zoom appropriately
map.centerAndZoom(new GPoint(-122.676258, 45.508272), 4);

</script>

Note that the main Google script goes in the <head> tag, which on Blogger means modifying your template and republishing your blog. If you are absolutely sure that you'll never have more than one post with maps on the same page, you could move that script into the body of the post. Multiple posts that did this on the same page would mean multiple includes of the script, which might upset some browsers.

The API provides additional methods for adding markers and labels and overlays... I'll probably write about those once I've messed around with this more.