Skip to content

Instantly share code, notes, and snippets.

@tommcfarlin
Last active April 1, 2016 16:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tommcfarlin/bc755df8f0011d10df4e to your computer and use it in GitHub Desktop.
Save tommcfarlin/bc755df8f0011d10df4e to your computer and use it in GitHub Desktop.
[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
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