正确的方法为谷歌地图json地理编码准备地址

时间:2017-02-09 10:02:03

标签: php google-maps

我正在尝试使用以下PHP脚本从地址获取lat和lng值:

    $address = "G & D KOI & AQUARIA, KLEINE VELD, DALEN, Nederland";
    $prepAddr = str_replace(' ','+',$address);
    $prepAddr = str_replace('&','%26',$prepAddr);
    $geocode = file_get_contents('https://maps.google.com/maps/api/geocode/json?address='.$prepAddr.'&sensor=false');
    $output= json_decode($geocode);
    $lat = $output->results[0]->geometry->location->lat;
    $lng = $output->results[0]->geometry->location->lng;

我正在用&替换%26。和' '用' +'。我需要照顾其他什么吗?

1 个答案:

答案 0 :(得分:1)

试试这个:

$prepAddr = urlencode($prepAddr);

并在您的API代码中使用$prepAddr,就像您使用的那样。

urlencode - 网址编码字符串

string urlencode ( string $str )

当编码要在URL的查询部分中使用的字符串时,此函数很方便,这是将变量传递到下一页的便捷方式。

相关问题