views:

527

answers:

2

I have a wordpress site with a large number of pages, each page represent a physical location. Now for each page I would like to display a google map based on the address. I know I can do this by installing for instance the Geo Mashup plugin http://wordpress.org/extend/plugins/geo-mashup/ but that requires (I believe) that I manually, for every post, create a location based on the address and add a shortcode to the post/page that results in a google map. This is a LOT of work for this site with hundreds of locations.

I would like to be able to

A: Create an "address-custom-field" for each post programmatically.
B: In a page template use that custom field to render a google map.

A is easy, but B?

+3  A: 

You may want to consider using the Google Maps API.

The following example may help you getting started. All you would need to do is to change the JavaScript variable yourAddress with the address of the location feature in your page. "If A is easy", that should be quite straight-forward.

<!DOCTYPE html>
<html> 
<head> 
    <meta http-equiv="content-type" content="text/html; charset=UTF-8"/> 
    <title>Google Maps API Demo</title> 
    <script src="http://maps.google.com/maps?file=api&amp;amp;v=2&amp;amp;sensor=false"
            type="text/javascript"></script> 
  </head> 
  <body onunload="GUnload()"> 

    <div id="map_canvas" style="width: 400px; height: 300px"></div> 

    <script type="text/javascript"> 

    var yourAddress = 'London, UK';

    if (GBrowserIsCompatible()) {
       var geocoder = new GClientGeocoder();
       geocoder.getLocations(yourAddress, function (locations) {         
          if (locations.Placemark)
          {
             var north = locations.Placemark[0].ExtendedData.LatLonBox.north;
             var south = locations.Placemark[0].ExtendedData.LatLonBox.south;
             var east  = locations.Placemark[0].ExtendedData.LatLonBox.east;
             var west  = locations.Placemark[0].ExtendedData.LatLonBox.west;

             var bounds = new GLatLngBounds(new GLatLng(south, west), 
                                            new GLatLng(north, east));

             var map = new GMap2(document.getElementById("map_canvas"));

             map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
          }
       });
    }
    </script> 
  </body> 
</html>

The above example would render a map like the one below:

Render google map in wordpress, based on address custom field

The map will not show if the Google Client-side Geocoder cannot retreive the coordinates from the address.

Daniel Vassallo
Thanks, that is perfect. I noticed that I have to add my Google Maps API key as a get parameter to the javascript call. (key=<mykey>)
windyjonas
@windyjonas: If you use the latest version of the Maps API (v3), you won't need a key.
Daniel Vassallo
A: 

that code rocks! How can we have it display a market with a name and address and directions?

ryan