谷歌地图无法打开流错误

时间:2016-10-04 11:34:47

标签: php google-maps file-get-contents

我正在上传一个csv文件并在$ address变量中获取地址字段,但是当我将$ address传递给谷歌地图时,它显示我错误,

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));

我错过了什么。 非常感谢任何帮助..谢谢

2 个答案:

答案 0 :(得分:1)

您需要使用google 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 :(得分:1)

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

有关差异的更多信息,请参见此处: Difference between "+" and "%A0" - urlencoding?

在此上下文中不接受%A0字符,但您可以对str_replace()的结果快速urlencode(),将所有这些特殊空格字符替换为+符号常规空间会导致。

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