Geocoding an Exploded Custom Field Array

This isn’t a complete answer, but a couple of bits of advice –

Don’t geocode the addresses on front-end requests, it’s a waste of cycles. An address only needs to be geocoded once, then you can store the lat/lon data with your post meta. Use a save_post hook to do the geocoding when the post is saved on the back-end.

You can geocode addresses with php like this:

$request_url = "http://maps.google.com/maps/geo?output=xml&q=" . urlencode($address);
$xml = simplexml_load_file( $request_url );
$status = $xml->Response->Status->code;
if( strcmp($status, "200" ) == 0 ):
    $coordinates = split( ',', $xml->Response->Placemark->Point->coordinates );
    $lat = $coordinates[1];
    $lon = $coordinates[0];
endif;

That’s just a quick example, you’ll want to add some error handling in there for geocode failures. See the Google Maps API docs for more info.

To get the location data into javascript, use wp_localize_script. You can add a filter to the_posts, which will give you an array of your posts and let you grab the post meta for each to localize the data for your script. Then when your script loads you’ll have access to that array to iterate over and place your markers.

Leave a Comment