从地址获取经度和纬度

时间:2015-05-21 13:10:47

标签: php google-maps

我无法弄清楚为什么我无法从这个地址获取坐标。 任何帮助表示赞赏。

 <?php

function getCoordinates($address){
    $mapApiKey= 'AIzaSyBaEjohZpjSWkzIXQP0u01FZpZSe5Uxuhs';
    $address = urlencode($address);
    $url = "https://maps.googleapis.com/maps/api/geocode/json?sensor=false&address=" .$address ."&key=".$mapApiKey;
    $response = file_get_contents($url);
    $json = json_decode($response,true);
    $lat = $json['results'][0]['geometry']['location']['lat'];
    $lng = $json['results'][0]['geometry']['location']['lng'];

 return array($lat, $lng);
  }

$coords = getCoordinates("Patras+Greece");
print_r($coords);
?>

1 个答案:

答案 0 :(得分:0)

而不是file_get_contents使用curl

$url = "http://maps.google.com/maps/api/geocode/json?address=".$address."&sensor=false";
                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL, $url);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                curl_setopt($ch, CURLOPT_PROXYPORT, 3128);
                curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
                $response = curl_exec($ch);
                curl_close($ch);
                $response_a = json_decode($response);
                if(isset($response_a))
                {
                $lat = $response_a->results[0]->geometry->location->lat;
                $long = $response_a->results[0]->geometry->location->lng;
}