Created
September 13, 2021 14:37
-
-
Save gzalinski/02abdf56f3543515bfe304fade005602 to your computer and use it in GitHub Desktop.
Address to geocode / coordinates
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
function geocode($address) | |
{ | |
// url encode the address | |
$address = urlencode($address); | |
$apiKey = GMAP_API_KEY; | |
// google map geocode api url | |
$url = "https://maps.googleapis.com/maps/api/geocode/json?address={$address}&key={$apiKey}"; | |
// get the json response | |
$resp_json = file_get_contents($url); | |
// decode the json | |
$resp = json_decode($resp_json, true); | |
// response status will be 'OK', if able to geocode given address | |
if ($resp['status'] == 'OK') { | |
// get the important data | |
$lat = isset($resp['results'][0]['geometry']['location']['lat']) ? $resp['results'][0]['geometry']['location']['lat'] : ""; | |
$lon = isset($resp['results'][0]['geometry']['location']['lng']) ? $resp['results'][0]['geometry']['location']['lng'] : ""; | |
$formatted_address = isset($resp['results'][0]['formatted_address']) ? $resp['results'][0]['formatted_address'] : ""; | |
// verify if data is complete | |
if ($lat && $lon && $formatted_address) { | |
// put the data in the array | |
return array( | |
'lat' => $lat, | |
'lon' => $lon, | |
'address' => $formatted_address | |
); | |
} else { | |
return false; | |
} | |
} else { | |
echo "<strong>ERROR: {$resp['status']}</strong>"; | |
return false; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment