Skip to content

Instantly share code, notes, and snippets.

@tommcfarlin tommcfarlin/1-save-coordinates.php Secret
Last active Apr 1, 2016

Embed
What would you like to do?
[WordPress] Saving latitude and longitude coordinates as a transient.
<?php
// Assume the address is not encoded so make sure it's encoded for URLs
$address = urlencode( $address );
// Conact Google Map for the JSON result
$result = file_get_contents( "https://maps.googleapis.com/maps/api/geocode/json?address=$address&key=YOUR_API_KEY" );
$result = json_decode( $result );
// Grab the latitude and longitude of the city
$lat = $result->results[0]->geometry->location->lat;
$lng = $result->results[0]->geometry->location->lng;
// Encode the address and store it in the addresses
$cities_to_map[] = array(
'adddress' => $address,
'latlong' => $lat . ',' . $lng,
'id' => $firm_id
);
// Store the values for 12 hours
set_transient( 'cities_to_map', $cities_to_map, 60 * 60 * 12 );
<?php
// Retrieve the addresses from the transient data
$stored_addresses = get_transient( 'cities_to_map' );
// If the transient doesn't exist, contact the Maps API
if ( FALSE === $stored_addresses ) {
// Assume the address is not encoded so make sure it's encoded for URLs
$address = urlencode( $address );
// Conact Google Map for the JSON result
$result = file_get_contents( "https://maps.googleapis.com/maps/api/geocode/json?address=$address&key=YOUR_API_KEY" );
$result = json_decode( $result );
// Grab the latitude and longitude of the city
$lat = $result->results[0]->geometry->location->lat;
$lng = $result->results[0]->geometry->location->lng;
// Encode the address and store it in the addresses
$cities_to_map[] = array(
'adddress' => $address,
'latlong' => $lat . ',' . $lng,
'id' => $firm_id
);
// Store the values for 12 hours
set_transient( 'cities_to_map', 60 * 60 * 12 );
}
@yratof

This comment has been minimized.

Copy link

yratof commented Apr 1, 2016

Say I have an array of 'london, newcastle, zimbabwe' – how would you approach saving this as a transient you can use, doesn't this work as only a single address as it is?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.