Last active
April 17, 2018 19:36
-
-
Save tallesairan/8a135bb2985f6b9aded76f9810af6ae9 to your computer and use it in GitHub Desktop.
Get city and state via google geocode api using latitude and longitude
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 | |
function simpleCachedCurl($url) { | |
$hash = md5($url); | |
$ch = curl_init(); | |
curl_setopt($ch, CURLOPT_URL, $url); | |
#curl_setopt( $ch, CURLOPT_COOKIEJAR, $cookie ); | |
curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, true ); | |
curl_setopt( $ch, CURLOPT_ENCODING, "utf-8" ); | |
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true ); | |
curl_setopt( $ch, CURLOPT_AUTOREFERER, true ); | |
curl_setopt($ch, CURLOPT_REFERER, $url); | |
curl_setopt($ch, CURLOPT_HTTPHEADER, array( | |
'Connection: Keep-Alive', | |
'Keep-Alive: 300' | |
)); | |
curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, false ); # required for https urls | |
curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT, 5000000000 ); | |
curl_setopt( $ch, CURLOPT_TIMEOUT, 5000000 ); | |
curl_setopt( $ch, CURLOPT_MAXREDIRS, 1000 ); | |
$rawData = curl_exec($ch); | |
curl_close($ch); | |
return $rawData; | |
} | |
$latlang = $_REQUEST['latlng']; | |
if(empty($latlang)){ | |
$latlang='-16.66070,-49.32504'; | |
} | |
function getCityandState($lat,$lng){ | |
$url = "https://maps.googleapis.com/maps/api/geocode/json?result_type=administrative_area_level_2|administrative_area_level_1&language=pt-BR&latlng=".$lat.",".$lng."&key=AIzaSyC2QfWZFQIWNGWMoPA4ynofit5vvw2WqV0"; | |
$maps = simpleCachedCurl($url); | |
$maps = json_decode($maps); | |
foreach($maps->results as $mapk => $map){ | |
foreach ($map->address_components as $mapAddress){ | |
if(in_array('administrative_area_level_2',$mapAddress->types)){ | |
$city = $mapAddress->short_name; | |
} | |
elseif(in_array('administrative_area_level_1',$mapAddress->types)) { | |
$state = $mapAddress->short_name; | |
} | |
} | |
break; | |
} | |
return ['city'=>$city,'state'=>$state]; | |
} | |
$cs=getCityandState('-16.66070','-49.32504'); | |
//$cs retorna Array ( [city] => Goiânia [state] => GO ) | |
// para pegar os valores basta usar $cs['city'] e $cs['state'] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment