2016-10-04 19 views
-1

我上传CSV文件,并在$地址变量中获得地址字段,但是当我通过$地址谷歌地图,它显示我的错误,谷歌地图未能打开流错误

file_get_contents(http://maps.googleapis.com/maps/api/geocode/json?address=9340+Middle+River+Street%A0%2COxford%2CMS%2C38655): failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request. 

我搜索它的解决方案,我发现一个只编码地址,但它也没有工作对我来说...

CODE

if (!empty($address)) { 
     $geo = file_get_contents('http://maps.googleapis.com/maps/api/geocode/json?address=' . urlencode($address)); 
     $geo = json_decode($geo, true); 
     if ($geo['status'] = 'OK') { 
      if (!empty($geo['results'][0])) { 
       $latitude = $geo['results'][0]['geometry']['location']['lat']; 
       $longitude = $geo['results'][0]['geometry']['location']['lng']; 
      } 
      $mapdata['latitude'] = $latitude; 
      $mapdata['longitude'] = $longitude; 
      return $mapdata; 
     } else { 
      $mapdata['latitude'] = ""; 
      $mapdata['longitude'] = ""; 
      return $mapdata; 
     } 
    } 

错误是在行

$geo = file_get_contents('http://maps.googleapis.com/maps/api/geocode/json?address=' . urlencode($address)); 

我错过了什么。 任何帮助是非常赞赏..谢谢

回答

1

你需要使用谷歌API密钥

function getLatLong($address){ 
    if(!empty($address)){ 
    //Formatted address 
    $formattedAddr = str_replace(' ','+',$address); 
    //Send request and receive json data by address 
    $geocodeFromAddr = file_get_contents('http://maps.googleapis.com/maps/api/geocode/json?address='.$formattedAddr.'&sensor=false'); 
    $output = json_decode($geocodeFromAddr); 
    //Get latitude and longitute from json data 
    $data['latitude'] = $output->results[0]->geometry->location->lat; 
    $data['longitude'] = $output->results[0]->geometry->location->lng; 
    //Return latitude and longitude of the given address 
    if(!empty($data)){ 
     return $data; 
    }else{ 
     return false; 
    } 
}else{ 
    return false; 
} 
} 

使用getLatLong(),如下面的函数。

$address = 'White House, Pennsylvania Avenue Northwest, Washington, DC, United States'; 
$latLong = getLatLong($address); 
$latitude = $latLong['latitude']?$latLong['latitude']:'Not found'; 
$longitude = $latLong['longitude']?$latLong['longitude']:'Not found'; 

要在您的请求中指定Google API密钥,请将其作为关键参数的值。

$geocodeFromAddr = file_get_contents('http://maps.googleapis.com/maps/api/geocode/json?address='.$formattedAddr.'&sensor=true_or_false&key=GoogleAPIKey'); 

我希望这会帮助你。

1

看起来问题在于你的数据集。由urlencode($address)编码为%A0的网址部分是一种特殊的不间断空格字符,而非常规空格。

看到这里的区别的详细信息: Difference between "+" and "%A0" - urlencoding?

%A0字符在此方面不接受,但你可以对urlencode()结果做一个快速的str_replace(),以取代所有这些特殊的空格字符标准空格产生的+符号。

$geo = file_get_contents('http://maps.googleapis.com/maps/api/geocode/json?address=' . str_replace('%A0', '+', urlencode($address)));