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);
		    infowindow.open(map, marker);
		  }
		})(marker, i));
	}
 
}
 
</script>

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:

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

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

  • Thank you, Marty! You very help me!

  • Hey Marty, thanks for all the tutorials!

    I got this working on a test site http://www.jenniferbin.com/world/ but not on my actual site http://blog.jenniferbin.com/travel/ . I was able to get the maps working without centering around the latest post but once I added the code for the centering, it stopped showing the map altogether. Any idea what I’m doing wrong?

    [repost since I can’t see where my last post went]

  • martyspellerberg

    Generally, I can help troubleshoot a stand-alone map that strictly follows the tutorial, but integration into an existing site is more than I can offer.

    But it looks like your marker images aren’t at the specified location, which could be contributing to the issue.

  • Ciaran

    I can’t get this to work. It seems that php won’t work in javascript but I’m not sure

  • Joe Fisher

    Is there a way to style infowindow? When I add an image I need to “clear both” to get the image contained in the infowindow div.

  • Salonglong

    Hello, I want to map displayed on the page.php, how to do?Thank you!

  • talk2toks

    Hello, Thanks for this tutorial, it has indeed being helpful. But the challenge am having is i want to be able to fetch post and display them on the map. This javascript code center: new google.maps.LatLng(38.898748, -77.037684), is not making the fetch queries to display on the map.

    Kindly assist in looking into this… It is quite urgent

  • Matt

    I’ve made a custom post type for class addresses and want to add a map to each post that has an address. How can I use this for that. I replaced the code you had in the initialize() to “$coordinates = get_post_meta( $post_id, ‘_ml_gkr_class_geo_coords’ );” where ml_gkr_class_geo_coords is the metabox. It doesn’t seem to work. Any help would be greatly appreciated.

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