-
-
Save tommcfarlin/bc755df8f0011d10df4e to your computer and use it in GitHub Desktop.
[WordPress] Saving latitude and longitude coordinates as a transient.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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 ); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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 ); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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?