0

So, I'm having a little problem with crossing signals in WordPress between Google Maps' API and an exploded custom field. I want to be able to geocode an address that's been exploded from a custom field, formatted "name,address":

<?php
$trucks = get_post_meta($post->ID, "truck", false);
if ($trucks[0]=="") { ?>

<p>No Trucks Operating Today</p>

<?php } else { ?>

<?php foreach($trucks as $truck) {
$truckdata = explode(',', $truck );
$name = $truckdata[0];
$location = $truckdata[1];
echo $name . ' is located at' . $location .'<br />'; ?>

<?php } ?>

This code will allow me to call each custom field, explode the value into its name and location into a separate value and echo them below.

What I want to do next is map out each value into a Google Map. Here's the code I'm working with:

    <script src="http://maps.google.com/maps/api/js?sensor=false" type="text/javascript"></script> 
    <script type="text/javascript"> 
        $(document).ready(function() { initialize(); });

        function initialize() {
            var map_options = {
                center: new google.maps.LatLng(33.84659,-84.35686),
                zoom: 14,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            };

            var google_map = new google.maps.Map(document.getElementById("map_canvas"), map_options);

            var info_window = new google.maps.InfoWindow({
                content: 'loading'
            });

            var t = [];
            var x = [];
            var y = [];
            var h = [];

            t.push('Location Name 1');
            x.push(33.84659);
            y.push(-84.35686);
            h.push('<p><strong>Location Name 1</strong><br/>Address 1</p>');

            t.push('Location Name 2');
            x.push(33.846253);
            y.push(-84.362125);
            h.push('<p><strong>Location Name 2</strong><br/>Address 2</p>');

            var i = 0;
            for ( item in t ) {
                var m = new google.maps.Marker({
                    map:       google_map,
                    animation: google.maps.Animation.DROP,
                    title:     t[i],
                    position:  new google.maps.LatLng(x[i],y[i]),
                    html:      h[i]
                });

                google.maps.event.addListener(m, 'click', function() {
                    info_window.setContent(this.html);
                    info_window.open(google_map, this);
                });
                i++;
            }
        }
    </script> 
    <div id="map_canvas" style="width:400px;height:400px;">Google Map</div> 

This is an example, but the code in question is the t, x, y, and h variables. I know I should be able to grab an address, pop it into a geocoder, and output a location for a marker. My question are:

1) how do I loop through my custom fields to grab the addresses inside of a javascript? Is there a way to grab the array with WP_Query (since it's only grabbing from one post) and use those variables in the javascript file?

2) how do I geocode the addresses and get them into the lat and lon positions in order to grab the correct coordinates for the markers

3) once I have the addresses geocoded, how can I get map markers placed that echo the sentiment below?

1
  • 2
    This is outside the scope of WordPress and better asked on stackoverflow.com, the questions are more related to PHP, js and Google maps.
    – Wyck
    Sep 9, 2012 at 14:38

1 Answer 1

1

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.