The code below gets the coordinates of an address/location using Google's Geocoding API, It works manually typing an address where I have written "ADDRESS GOES HERE" below, doing so then outputs the coordinates appropriately.
<?php
function getCoordinates($address) {
$address = urlencode($address);
// set HTTP header
$headers = array('Content-Type: application/json');
// Open connection
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'http://maps.google.com/maps/api/geocode/json?sensor=false&address=' . $address);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
// Execute request
$result = curl_exec($curl);
// Close connection
curl_close($curl);
// get the result and parse to JSON
$json = json_decode($result);
$lat = $json->results[0]->geometry->location->lat;
$lng = $json->results[0]->geometry->location->lng;
return array($lat, $lng);
}
$coords = getCoordinates("ADDRESS GOES HERE ");
$coords = join(',', $coords);
?>
What id now like to do now, is use custom fields (ACF) to call the addresses dynamically into "ADDRESS GOES HERE".
The fields that contain the addresses are currently called into a template currently like this :
<?php if( get_field('address_line_1') ): ?><?php the_title(); ?>, <?php the_field('address_line_1', $post_id); ?>,<?php the_field('address_line_2', $post_id); ?>, <?php the_field('town', $post_id); ?>, <?php the_field('post_code', $post_id); ?>, <?php the_field('country', $post_id); ?><?php endif; ?>
Whats the best way to use the above field in the "Address goes here" location ?
For reference the curl script is a spin off of https://colinyeoh.wordpress.com/2013/02/12/simple-php-function-to-get-coordinates-from-address-through-google-services/, which didnt seem to work as effectively.
get_field
is not a WordPress function. where does it come from ?getCoordinates()
defined/run? You're usingcurl()
directly, which implies that this isn't in a WordPress context?