Leave a Reply

1 comment

  1. There is no need to put them into an array. According to google’s documentation you should just separate out the various pieces of the address in the url like a standard (U.S.) formatted address.

    // Example taken from google's docs:
    $state = 'CA';
    $street = 'Mountain View';
    $address = '1600 Amphitheatre Parkway';
    
    function geocode_address($post_id)
    {
        $custom_fields = get_post_custom();
    
        // just set $city, $state and $address to the appropriate custom field variables here
    
        if(isset($custom_fields['state']) && !empty($custom_fields['state'][0]))
        {
    
     $resp = wp_remote_get( "http://maps.googleapis.com/maps/api/geocode/json?address=".urlencode($address . ',' . $city . ',' .$state)."&sensor=false" );
                if ( 200 == $resp['response']['code'] ) {
                        $body = $resp['body'];
                        $data = json_decode($body);
                        if($data->status=="OK"){
                                $latitude = $data->results[0]->geometry->location->lat;
                                $longitude = $data->results[0]->geometry->location->lng;
                                update_post_meta($post_id, "latitude", $latitude);
                                update_post_meta($post_id, "longitude", $longitude);
                        }
                }
        }
    }
    add_action('save_post', 'geocode_address');