Saturday, 22 November 2008

Easy Map Embedding

Every since starting the development of TagME I've been thinking about finding an easy way of showing the geotagged photos on my blog. Now it is quite easy to display a KMZ file in Google Maps (and of course Google Earth) using the simple method Google provides. Unfortunately this method doesn't allow you to access all the features of the Google Maps API. So to allow me more flexibility I've written some javascript to allow for easy map embedding. Here is the script in action:



To achieve this you need to have already loaded the Google Maps API and then in the head section of your page load my KMLMapLoader. The when you want to embed a map you create a DIV to contain it. For example, to create the map I showed above you add the following to your page:
<div kml="http://www.dcs.shef.ac.uk/~mark/blog/blog_files/journeys/to_work_updated.kmz"
zoom="11" latitude="53.4717" longitude="-1.511993"
maptype="G_PHYSICAL_MAP"
config="map.addControl(new GLargeMapControl());"
style="border: 1px solid black; width: 600px; height: 700px;">
</div>
It is reasonable straightforward but here is an explanation of the different attributes you can set:
kml
This should be the URL of the KML or KMZ file you wish to display on the map.

latitude
The latitude of the centre of the map.

longitude
The longitude of the centre of the map.

zoom
The zoom level (level 0 shows the whole earth, each increase in zoom level increase the area seen be a power of 2).

maptype
The map type. The default is the street level map, but you can specify any of the types Google supports. Note that id you specify G_SATELLITE_3D_MAP and the Google Earth plugin isn't installed then rather than an error message the script will revert to using G_SATELLITE_MAP

config
If specified this should be JavaScript that will be executed once the map has been initialised. The map itself is available in the variable map and this can be used to further configure the map (for example adding a large map control rather than the default small control the script uses).
Only the kml attribute is required, but to set the location of the map latitude, longitude and zoom must all be specified.

The script actually does a little more than loading the map, it also provides a fix for a bug in the current version of the Google Maps API. When loading a KMZ file the images etc are accessed through a server side script. Unfortunately the API uses a relative URL to point to this script and so KMZ files display properly if loaded through the main Google Maps website but not when loaded using the API. KMLMapLoader adds code to fix this bug which you can reuse even if you don't want to use the loading facilities.

Post a Comment