A back-to-basics tutorial for generating a geoRSS feed from WordPress, correctly formatted for use in Google Maps KML layers.
There are a profusion of (often very full-featured and cool) WordPress plugins out there providing geolocation or geotagging functionality. However, none of them really fit my purposes for any or all of the following reasons:
- they use geolocation data from the blogger who is writing the post, as opposed to manually-entered coordinates.
- they are focussed on providing mapping within WordPress, as opposed to generating a feed for use externally.
- they added unnecessary calls to Google or Yahoo scripts in
wp_head(). - they used out-of-date versions of the Google Maps API.
gPress is currently the most promising-looking complete package for mapping in WordPress, and it apparently offers geoRSS functionality, although I haven’t checked it out yet. However, I simply wanted to provide a geoRSS feed without any additional baggage, besides wanting to build the nuts and bolts myself.
Generating a new feed
In functions.php, add the following:
add_action('init', 'my_maps_init');
function my_maps_init() {
add_feed('georss','my_georss_feed');
}
function my_georss_feed() {
load_template( TEMPLATEPATH . '/feed-georss.php' );
}
Now you can create your new feed-georss.php template. I based my code on the output from Flickr’s geoRSS feed, as used in this example. It contains latitude and longitude coordinates from two new custom fields set up in the post itself. Note the special RSS template tags e.g. the_title_rss() that strip out tags and convert characters to present the raw data via RSS.
Assuming you have some posts ready with geo-coordinates in custom fields, you can test the feed output at:
http://www.yourblog.com/?feed=georss
If you are only adding coordinates to posts in certain categories you can also use e.g.:
http://www.yourblog.com/category/maps/?feed=georss
Google Maps
Assuming your feed is working correctly, you can now get your geotagged posts to show up on a Google map using a KML Layer. You’ll need to read up on the documentation first, but for reference here’s the relevant snippet of my code:
var kmlLayerOptions = {
map: map,
preserveViewport: true,
suppressInfoWindows: true
}
var georssLayer = new google.maps.KmlLayer('http://blogs.fashion.arts.ac.uk/snapshot/category/international/?feed=georss', kmlLayerOptions);
google.maps.event.addListener(georssLayer, 'click', function(kmlEvent) {
showKmlWindow(kmlEvent, georssLayer);
});
function showKmlWindow(e, layer) {
infoWindow.close();
infoWindow.setPosition(e.latLng);
infoWindow.open(map);
infoWindow.setContent('<h3>' + e.featureData.name + '</h3>' + e.featureData.description);
}
Note that, in order to manipulate the infoWindow content when each marker is clicked, you have to suppress the infoWindows that open automatically. You then catch the kmlEvent generated on click, and then do what you will with the KmlFeatureData object.