Skip to content

Instantly share code, notes, and snippets.

@talcual
Created February 7, 2020 03:47
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 talcual/03111619f4914566c5a71d4be76a9699 to your computer and use it in GitHub Desktop.
Save talcual/03111619f4914566c5a71d4be76a9699 to your computer and use it in GitHub Desktop.
<?php
class utils{
public static function geocode($address){
// url encode the address
$address = urlencode($address);
// google map geocode api url
$url = "https://maps.googleapis.com/maps/api/geocode/json?address={$address}&key=thegooglemapskey";
// 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
$lati = isset($resp['results'][0]['geometry']['location']['lat']) ? $resp['results'][0]['geometry']['location']['lat'] : "";
$longi = 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($lati && $longi && $formatted_address){
// put the data in the array
$data_arr = array();
array_push(
$data_arr,
$lati,
$longi,
$formatted_address
);
return $data_arr;
}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