如何使用谷歌地图从坐标中获取城市名称

时间:2021-05-04 00:58:25

标签: php geocoding

我正在使用以下代码,但无法使其正常工作。它应该获取坐标并返回一个城市名称

<?php
function getAddress($lat, $lon) {
    $url = "http://maps.googleapis.com/maps/api/geocode/json?latlng=".
    $lat.",".$lon."&sensor=false";
    $json = @file_get_contents($url);
    $data = json_decode($json);
    $status = $data->status;
    $address = '';
    if($status == "OK"){
        foreach($data->results[0]->address_components as $address_component) {
            if(in_array('street_number', $address_component->types)) {
                $street_number = $address_component->long_name;
            }
            if(in_array('route', $address_component->types)) {
                 $route = $address_component->long_name;
            }
        }
    }
    return $street_number." ".$route;
}

echo getAddress(-1.566120,53.824);

但是,它返回一个空白的白页。我究竟做错了什么? 请帮忙。

-- 更新代码-- 稍微简化..

 <?php
    
        $url = "https://maps.googleapis.com/maps/api/geocode/json?latlng=44,44&key=<your-key-here>&sensor=false";
        $json = @file_get_contents($url);
        $data = json_decode($json);
        $status = $data->status;
        $address = '';
        if($status == "OK"){
            foreach($data->results[0]->address_components as $address_component) {
                if(in_array('street_number', $address_component->types)) {
                    $street_number = $address_component->long_name;
                }
                if(in_array('route', $address_component->types)) {
                     $route = $address_component->long_name;
                }
            }
        }
        echo $street_number." ".$route;
    
    ?>

仍在寻找 awnsers :)

1 个答案:

答案 0 :(得分:1)

Google Maps API 需要在 URL 中传递 API 密钥,如下面的示例所示。

https://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452&key=YOUR_API_KEY

请注意,上面的 URL 是 HTTPS,而不是 HTTP。 HTTP 不再适用于 Google API。

正如@catcon 所说,您需要在 Google Cloud 项目上启用计费。

但是,为了避免出现空白页面,我建议更改以下代码。

改变这个

...
$json = @file_get_contents($url);
...

到这里

...
$json = @file_get_contents($url);
if ($json['status'] != 'OK') {
  return $json;
}
...

这将允许您在 API 调用失败时查看结果。