Center a Google Map on the Latest WordPress Post

This is a follow-up to my previous post on integrating WordPress and Google Maps. Damien asks:

“Would it be possible to centre the map on my latest post?”

Yes, it is!

This builds off the example in the previous post and I’m using the Address Geocoder plugin to set latlngs. You can see and download the entire working example at GitHub.

Output the JavaScript with PHP

The line that defines the center of the map is presently specified in a static way — we arbitrarily chose a location and included its latlng in the JavaScript function initialize(). Now we will revise this so that it is pulling a dynamic variable from WordPress. There are a number of ways to accomplish this, but here we’re going to go with the most straightforward, which is to move the entire contents of the static maps.js into the dynamic index.php.

Open maps.js and copy the contents to your clipboard. Then open index.php and look for this line:

<script type="text/javascript" src="<?php echo get_stylesheet_directory_uri() ?>/map.js"></script>

Remove the src parameter and paste the JavaScript between the opening and closing tags so that you have this:

<script type="text/javascript">
var infowindow = new google.maps.InfoWindow();
var pinkmarker = new google.maps.MarkerImage('/wp-content/themes/mapdemo/pink_Marker.png', new google.maps.Size(20, 34) );
var shadow = new google.maps.MarkerImage('/wp-content/themes/mapdemo/shadow.png', new google.maps.Size(37, 34) );
function initialize() {
	map = new google.maps.Map(document.getElementById('map'), { 
		zoom: 12, 
		center: new google.maps.LatLng(38.898748, -77.037684), 
		mapTypeId: google.maps.MapTypeId.ROADMAP 
	for (var i = 0; i < locations.length; i++) {  
		var marker = new google.maps.Marker({
	    	position: locations[i].latlng,
			icon: pinkmarker,
			shadow: shadow,
			map: map
		google.maps.event.addListener(marker, 'click', (function(marker, i) {
		  return function() {
		    infowindow.setContent(locations[i].info);, marker);
		})(marker, i));

Next we are going to add in a simple WordPress loop to get the single latest post and assign its latlng to a PHP variable.

Right inside the initialize() function, before the definition of map, add:

$the_query = new WP_Query('showposts=1');
while ( $the_query->have_posts() ) : $the_query->the_post();
	$coordinates = get_geocode_latlng($post->ID);

And lastly, output that variable to the line that defines the map’s center, in place the static latlng. Look for this line:

center: new google.maps.LatLng(38.898748, -77.037684),

And change it to this:

center: new google.maps.LatLng<?php echo $coordinates ?>,

Done! On load, your map will now center on the marker of the latest post.

Posted July 2012

This website is hosted by Media Temple. Thanks, guys!