WordPress: Custom Fields & Google Maps API

WordPress is probably by far the most popular blogging platform out there today, having a high level of customization that can turn the software into a CMS while being driven by a community geared toward open minds and development. I absolutely love WordPress as a web designer and it pushes me daily to discover more of what this platform can handle. Now lets get on with the post.

WordPress has a feature called Custom Fields that are for posts containing data not within the post’s body, but rather hidden within the post from plain site. The great thing about Custom Fields is that you can use it for just about anything.

While still working on the development of the Douglas County Film Commission website, certain posts are used for shooting locations and each location post had to have a map of the area present for viewing. I had tried different ways to integrate the Google Maps API into the website, from placing the info in the header to installing various WordPress plug-ins, all of which did not work for the purpose of the website.

Discouraged with the results, I took a crack at implementing Google Maps in a post by passing data through custom fields. And believe it or not, it actually worked with very little code. If this is your first time working with Google Maps API, check out Google’s tutorial on building your first map. Here’s how to do it on your own.

By the way, this if my first ever tutorial so be gentle.

1. Grab a Google Maps API Key
First and foremost, you need to sign up for a free Google Maps API Key. Without it you are dead in the water and this post will no longer pertain to you. The key is a long set of letters and numbers, so copy and paste it somewhere for safe keeping.

2. Edit Your Template – Single.php
Now that you have your Google Maps API Key, its time to edit your single.php file to allow a map to appear using custom fields. In this case, I used the Google Maps AJAX API Loader. For the custom field I will name it gps and set up an if statement to see whether it has data or not.

<? $gps = get_post_meta($post->ID, 'gps', $single = true); //GPS info for location using Google Maps API
if($gps !== '') { ?>

Now add in the code for the Google Maps AJAX API using the key you just obtained earlier. Since this is the AJAX API, you have to tell Google that you want to use the Maps API.

<script type="text/javascript" src="http://www.google.com/jsapi?key=ABCDEFG"></script>

<script type="text/javascript">
     google.load("maps", "2");

For the loading the map you will use the gps custom field that was declared earlier. In this part you will initialize the map for the div you want it to appear in and set up the zoom.

// Call this function when the page has been loaded
function initialize() {

if (GBrowserIsCompatible()) {
	var map = new google.maps.Map2(document.getElementById("map_canvas"));
	map.setCenter(new google.maps.LatLng(<?php echo $gps; ?>), 17);

Time to add some controls to the map. With the DCFC site I was limited on space so I opted for the small controls on both the zoom and map types.

// map controls
map.setMapType(G_HYBRID_MAP);
map.addControl(new GSmallMapControl());
map.addControl(new GMenuMapTypeControl());

The addition of a marker for the specific location listed.

// marker for location
var marker = new GMarker(new GLatLng(<?php echo $gps; ?>));
map.addOverlay(marker);

Lastly close up both functions and call for the map to appear.

}

  }
  google.setOnLoadCallback(initialize);

</script>

Your code should look something like this:

<? $gps = get_post_meta($post->ID, 'gps', $single = true); //GPS info for location using Google Maps API
    //if there are gps coordinates, build map
    if($gps !== '') { ?>

   <script type="text/javascript" src="http://www.google.com/jsapi?key=ABCDEFG"></script>
    <script type="text/javascript">
      google.load("maps", "2");

      // Call this function when the page has been loaded
      function initialize() {

        if (GBrowserIsCompatible()) {
        var map = new google.maps.Map2(document.getElementById("map_canvas"));
        map.setCenter(new google.maps.LatLng(<?php echo $gps; ?>), 17);

        // map controls
        map.setMapType(G_HYBRID_MAP);
        map.addControl(new GSmallMapControl());
        map.addControl(new GMenuMapTypeControl());

        // marker for location
        var marker = new GMarker(new GLatLng(<?php echo $gps; ?>));
        map.addOverlay(marker);
      }
      }
      google.setOnLoadCallback(initialize);

    </script>

Now that the hard part is done, you have to declare the div that the map will appear. In this example I chose to use map_canvas as my div id. Unfortunately you can not edit your CSS stylesheet to stylize the div. Instead you have to code it within the div, in this case its just the size.

<div id="map_canvas" style="margin: 0; padding: 0; width: 460px; height: 250px;">
</div><!-- #map_canvas -->
<?php } else {}?>

Save single.php and upload to your sever.

3. Write a Post
Log-in to your website and write a new post. In the Custom Fields section you want to name the key gps and for the value put in the coordinates, for instance I will use 33.743808,-84.743321. Publish the post and view your work.

Custom Field with variable gps

4. That’s it!
As you can see it was fairly easy to implement Google Maps into a post with little editing to your template. With custom fields you can add all kind of data to the map – or to a post for that matter. Happy trails.

Now check it out in action over at the Douglas County Film Commission website.

Google Map

6 Responses to “WordPress: Custom Fields & Google Maps API”

  1. Matt

    11:04 am on July 11th, 2008

    Hey, great little tutorial. I’m used to messing with the Google Maps API in PHP or Drupal.

    Now I’m trying to set one up for some friends on their new Wordpress site I made for their band.

    I’m not seeing results with this. Can you perhaps look and offer any help/suggestions/ideas?

    http://s93101162.onlinehome.us/beta/?page_id=74

    Thanks,

    Matt

  2. Andrew Powell

    11:25 am on July 11th, 2008

    @Matt

    Looks like I goofed in the markup - forgot to start off the php.

    Damn, looks like I need to CSS my comments

  3. Pixelguy

    3:44 am on August 8th, 2008

    is there any possibility to enter real names like new york instead of the abstract coordinates?

  4. Andrew Powell

    8:06 am on August 8th, 2008

    @Pixelguy

    Unfortunately no, the Google Maps API functions only allow lat/long coordinates in numerical form based on Google Maps

  5. toure

    12:24 pm on October 6th, 2008

    Great tutorial, but I was wondering if I have to delete the original content of the single.php file or put the map api code before or after calling the_post?
    Thanks for your help

  6. Andrew Powell

    3:05 pm on October 6th, 2008

    @ toure

    put it after you’ve called the post - custom fields must be pulled from the post where the information is stored

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Purchase an autographed copy of The Residual Solace

About Andrew

Andrew A. Powell is a native of Douglasville, Georgia and works as a freelance photographer and website developer.

404.732.4567
andrew[@]traderelic.com

Check me out on Facebook Check me out on Last.fm

Skills

  • Website Design + Development
  • PSD to XHTML + CSS
  • WordPress as CMS
  • Website Administration
  • Design Consultation
  • Digital Photography