Google Maps API

In a recent project it was asked to provide a Google map on a number of pages. It would have been too time consuming to create a custom map and manually place the code on each page. Instead using the Google Maps API was a better choice because the address could be pulled from a custom field in the post and used to create the map. With the code below adding a Google Map is simple.

The first step is signing up for a API key, as with most Google products is free and only requires a Google account. After you’ve received your key, you can then edit the functions.php file of your current theme. The below code has some key spots to take note of and maybe change some values. I will highlight these after the full code.

<?php 
add_action('wp_head', 'gmaps_header');

function gmaps_header() {
?>
	<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&key=YOURAPIKEYGOESHERE"></script>
<?php
}

function google_map(){
	global $post;
	$post_id = get_the_ID();
	$address = get_post_meta($post_id, 'address', true);
	if ( !empty ($address ) ){ ?>
		<div id="google_map" style="width:500px;height:400px;"></div><br />
		<form onsubmit="calcRoute();return false;">
			<input type="text" id="start" value="">
			<input type="submit" value="Get directions">
		</form><br />
		<div id="directionsPanel" style="width:500px;"></div>
		<script type="text/javascript">
			var directionDisplay;
			var directionsService = new google.maps.DirectionsService();
			directionsDisplay = new google.maps.DirectionsRenderer();
			var latlng = new google.maps.LatLng(0,0);
			var myOptions = {
				zoom: 7,
				center: latlng,
				mapTypeControl: true,
				mapTypeId: google.maps.MapTypeId.HYBRID
			};
			var google_map = new google.maps.Map(document.getElementById("google_map"), myOptions);
			directionsDisplay.setMap(google_map);
			directionsDisplay.setPanel(document.getElementById("directionsPanel"))
			var geocoder_google_map = new google.maps.Geocoder();
			var address = '<?php echo $address ?>';
			geocoder_google_map.geocode( { 'address': address}, function(results, status) {
				if (status == google.maps.GeocoderStatus.OK) {
					google_map.setCenter(results[0].geometry.location);
					var marker = new google.maps.Marker({
						map: google_map,
						position: google_map.getCenter()
						});
						<?php $thiscontent = $address;?>
						var contentString = '<?php echo $thiscontent; ?>';
						var infowindow = new google.maps.InfoWindow({
							content: contentString
						});
						infowindow.open(google_map,marker);			
						google.maps.event.addListener(marker, 'click', function() {
							infowindow.open(google_map,marker);
						});
				
					} else {
						alert("Geocode was not successful for the following reason: " + status);
					}
				});
					
			function calcRoute() {
				var address = '<?php echo $address ?>';
				var start = document.getElementById("start").value;
				var request = {
					origin:start, 
					destination:address,
					travelMode: google.maps.DirectionsTravelMode.DRIVING
				};
				directionsService.route(request, function(response, status) {
				  if (status == google.maps.DirectionsStatus.OK) {
					directionsDisplay.setDirections(response);
				  }
				});
			}
		</script>
<?php
	}

}?>

After you have your API key it will need to be added to this line.

	<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&key=YOURAPIKEYGOESHERE"></script>

Here is the container that will hold the map. The width and height can be changed to better suit the current theme.

<div id="google_map" style="width:500px;height:400px;"></div><br />

The same with this line, which holds the driving directions panel. Here only a width is specified to allow the directions to use as much height as needed.

 <div id="directionsPanel" style="width:500px;"></div>

If driving directions aren’t need the simply removing these lines will remove the form and the container for the directions.

	<form onsubmit="calcRoute();return false;">
	<input type="text" id="start" value="">
	<input type="submit" value="Get directions">
	</form><br />
	<div id="directionsPanel" style="width:500px;"></div>

Another important section is the map options themselves. Zoom controls the how far the map is zoomed by default, mapTypeControl tells whether or not you want the controls for zoom and changing map type on the map. The mapTypeId tells what kind of map you want displayed by default, HYBRID is the satellite view with the roads overlayed. A list of possible mapTypeId is here.

				zoom: 7,
				center: latlng,
				mapTypeControl: true,
				mapTypeId: google.maps.MapTypeId.HYBRID

The marker content can be customized by setting the $thiscontent variable. The address is shown by default, but any html can be added to the marker. Other things you might consider is the places name, phone number, this can all be set via custom fields, and appended to the $thiscontent variable.

						<?php $thiscontent = $address;?>

After you’ve customized and added the code to your functions.php file, you can then edit your single.php and use this to display the maps where you would like.

&lt;?php echo google_map(); ?&gt;

Then in your post just add a custom field with the name address and the contents a valid and correctly formated address, the code will do the rest.

Resources:

Maps API Reference

About Jeremy Clark

Small town IT worker with interests in all things technological and technical. Biggest interests are in web development especially the WordPress publishing platform and the community supporting it. Currently developing and maintain the free WordPress theme Techozoic. I'm also always available for hire.
This entry was posted in wordpress and tagged , , , , , , . Bookmark the permalink.

Leave a reply

Comments will be sent to the moderation queue.