Technology, life, programming, travel and money.

Adding KML Google Maps overlays to WordPress posts

Embedding basic KML Maps into your blog post

There is an easy way to include Google Maps KML overlays in your WordPress blog if you are willing to have all the size and style information hardcoded into each post. All you have to do is to go to http://maps.google.co.uk/ type the KML location into the search box and then click on ‘Link to this page’.

Embedding KML into your WordPress blog using Google Maps

You can then add the HTML into your blog post by copy / pasting it from the second text box.

HTML for embedding Google Maps in a WordPress blog post

Google make it easy to change simple settings such as the map size by following the ‘Customise…’ link. Below is what the actual embedded map would look like. Handily the map is automatically zoomed into whatever data is in your KML file – In this example we’re looking at a walking track across London.


View Larger Map

This is great for if you want to add the odd maps to your blog, or if you don’t believe you’ll need to alter the style later on. The problem comes if you want to separate all the style information out of the embedded map iframe.

The problem with the Google Maps HTML generator

Imagine if you had a site with dozens or even hundreds of embedded KML files. One day in the future you decide that you want to change the style and look of all the maps. Maybe you want to change the size, add some extra links under each map, or add new features from the Google Maps API to each map. Below is what the actual HTML code embedding this KML file looks like. As you can see it is pretty ugly and it wouldn’t be fun to edit dozens / hundreds of these to change the way they look.

<iframe width="425" height="350" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="http://maps.google.co.uk/maps?f=q&amp;hl=en&amp;geocode=&amp;time=&amp;date=&amp;ttype=&amp;q=http:%2F%2Fwww.reviewmylife.co.uk%2Fdata%2F071220%2Ftrack_east_london.kml&amp;ie=UTF8&amp;ll=51.497414,-0.054315&amp;spn=0.044967,0.044325&amp;om=0&amp;output=embed&amp;s=AARTsJozG9M05ndgSB8zlZU1Qavi7qH_cw"></iframe><br /><small><a href="http://maps.google.co.uk/maps?f=q&amp;hl=en&amp;geocode=&amp;time=&amp;date=&amp;ttype=&amp;q=http:%2F%2Fwww.reviewmylife.co.uk%2Fdata%2F071220%2Ftrack_east_london.kml&amp;ie=UTF8&amp;ll=51.497414,-0.054315&amp;spn=0.044967,0.044325&amp;om=0&amp;source=embed" style="color:#0000FF;text-align:left">View Larger Map</a></small>

Under normal circumstances it would be easy to separate out this code into a different file and pass in the KML file URL as a parameter. The problem is that Google have added a security parameter to the argument list (s=AARTsJozG9M05ndgSB8zlZU1Qavi7qH_cw in this case) which locks in the KML URL. You can edit the style parameters (width / height etc) but you can’t change the URL. If you do you get an error saying “Forbidden Your client does not have permission to get URL…”. Google have done this so they can keep a track of how much load individual sites are putting on their server. Unfortunately it means that if you want to use a new KML you have to use the Google Maps site to generate the HTML.

A solution and another problem for WordPress bloggers

There is a way around this, and that is to use the Google Maps API. This will allow you to programatically include as many KMLs as you want without using Google’s HTML generator. To use the API you have to sign up for a Google Maps API Key. There is one final problem – each key can only be used from one individual web directory. This can be a big problem if you are a WordPress user. Bill from the techrageo blog has already written about this so I won’t repeat what he has said. You can read his blog and look at his solution for yourself.

There are however some problems with his solution.

  1. You would need to create a new HTML file for each Google Map you are embedding.
  2. The width and height of the iframe have to be embedded in each map in each blog post or HTML page that you use it on.
  3. The JavaScript in his solution doesn’t quite do what I want.

Here is my solution which is inspired by his but solves these three issues. Please note that as with Bill’s solution this will require some programming knowledge. You will need to make modifications to my scripts to get them to work on your site.

To embed a KML file with my solution all you have to do is include a small section of PHP in your blog post. To allow me to embed PHP in my blog posts I’ve installed the Exec-PHP plugin. This is what the PHP looks like.

<?php
$mapxml="http://www.reviewmylife.co.uk/mymap.kml";
require('../data/kml/mapiframe.php');
?>

You must set the $mapxml variable which points to your KML file – it has to be the full URL, not a relative one. You then load the mapiframe.php file with the ‘require’ command. Optionally you can set a $width and a $height variable for the width/height in pixels, but this will re-introduce problem number 2. If you don’t set these values then default sizes (which you can change) will be used.

Embedding the KML with this PHP means that your blog posts now don’t contain any formatting infomation for the maps. All the formatting can be controlled from the following common scripts.

This is what your mapiframe.php looks like, it contains the common iframe information. You will probably need to fix the link to the loadmap.php file for your own web server.

<?php
/*
Include a KML on WordPress Blog
See www.reviewmylife.co.uk for details.
*/
if (!isset($mapxml))
	{
	print "ERROR: Missing mapxml";
	exit;
	}
if (!isset($width))
	{
	$width = "450";
	}
if (!isset($height))
	{
	$height = "450";
	}
$mapxml = urlencode($mapxml);
$widthparam="width=$width";
$heightparam="height=$height";
print <<<ENDHTML
<iframe width="$width" height="$height" scrolling="no"
frameborder="0" marginheight="0" marginwidth="0"
src="/data/kml/loadmap.php?mapxml=$mapxml&amp;$widthparam&amp;$heightparam">
If you see this, your browser doesn't support iframes.
Please upgrade to a more recent browser.</iframe><br /><small>
<a href="http://maps.google.co.uk/maps?f=q&amp;hl=en&amp;q=$mapxml&amp;ie=UTF8&amp;om=1&amp;source=embed"
style="color:#0000FF;text-align:left">View Larger Map</a></small>
ENDHTML
?>

Here is the code for loadmap.php. You’ll need to replace the Google Maps API key with your own one.

<?php
/*
Include a KML on WordPress Blog
See www.reviewmylife.co.uk for details.
Remember to replace the Google API key with your
own one or this script won't work!
*/
if (!isset($mapxml))
	{
	print "ERROR: Missing mapxml";
	exit;
	}
if (!isset($width))
	{
	$width = "450";
	}
if (!isset($height))
	{
	$height = "450";
	}
print <<<ENDHTML
<html>
<head>
  <title>Google Map Loader - $mapxml</title>
  <script src="http://maps.google.com/maps?file=api&v=2&key=ABQIAAAA6Y9TsXMv7cdqyP8VLw2boRSTFKCAindh81v9qdSRu-QtalZoMBQj6TDiTZizmDy7aoJTqU6iO3pDOQ" type="text/javascript"></script>
  <script src="googlemaploader.js"></script>
</head>
<body onload="initialize()" onunload="GUnload()">
<div id="map" style="width:$width; height:$height"></div>
<span id="mapxml" name="$mapxml"></span>
<script type="text/javascript">
 function initialize() {
  if (GBrowserIsCompatible()){
   LoadGoogleMap();
   }
  }
</script>
</body>
</html>
ENDHTML
?>

This is the googlemaploader.js file which loads the KML using the Google Maps API. It correctly sets the viewport in the map view and adds a few controls to the map.

// Script to load and position a KML/XML Google Map
// See www.reviewmylife.co.uk for details.
var kml;
function LoadGoogleMap(){
  // Find mapinfo span and get name attribute
  var mapxml = document.getElementById('mapxml').getAttribute('name');
  kml = new GGeoXml(mapxml, PositionMapCallback);
}
function PositionMapCallback(){
  var map = new GMap2(document.getElementById("map"));
  map.addControl(new GSmallMapControl());
  map.addControl(new GMapTypeControl());
  kml.gotoDefaultViewport(map);
  map.addOverlay(kml);
}

This is the final result. Yes it looks very similar to the one generated by the Google Maps HTML generator. But if I ever need to change all my embedded maps it will be really easy for me.


View Larger Map
Here are some download links for the three files you need.

MapIframe.php
LoadMap.php
GoogleMapLoader.js

You’ll need to change the Google API key in loadmap.php. You’ll also need to fix the inter-file references so all the scripts reference each other correctly. All three scripts should be placed in the directory that you created the Google API key for.

Update: Make sure you check out my Improved KML embedding of Google Maps into web pages post for some updates to these scripts.


Reader Feedback

One Response to “Adding KML Google Maps overlays to WordPress posts”

  1. bill weaver says:

    Nice solution. I’m glad you found my article of some use, and like your variant. Isn’t it a shame that we have to jump through all these hoops to stick a map in a WordPress post? What an amazing mess, that that article from over two years ago is still one of the most popular at techrageo.us and that some solution like yours or mine is still required — two years is a long time in the tech world.

Leave a Reply

Do NOT fill this !