【问题标题】:best way to get city name from google reverse geocoding api php从谷歌反向地理编码api php获取城市名称的最佳方法
【发布时间】:2017-03-16 09:40:10
【问题描述】:

我正在尝试从谷歌反向地理编码 api 获取城市名称,我的代码显示该位置的完整地址,但我只需要城市。下面是我的代码

<?php
session_start();
if(!empty($_POST['latitude']) && !empty($_POST['longitude'])){
    //Send request and receive json data by latitude and longitude
    $url = 'http://maps.googleapis.com/maps/api/geocode/json?latlng='.trim($_POST['latitude']).','.trim($_POST['longitude']).'&sensor=false';
    $json = @file_get_contents($url);
    $data = json_decode($json);
    $status = $data->status;
    if($status=="OK"){
        //Get address from json data
        //$location = $data->results[0]->formatted_address;
        $location = $data->results[0]->address_components;

    }else{
        $location =  '';
    }
    //Print city
    $_SESSION['getgeoloc']=$location[6]->long_name;

    echo $location;
}
?>

我尝试使用以下代码显示城市,但有时显示邮政编码,有时显示城市名称

$_SESSION['getgeoloc']=$location[6]->long_name;

有没有最好的方法?

【问题讨论】:

  • 我认为这是因为每个位置都有不同类型的数据,并且在其中形成不同的数组。不是吗?
  • 是的,那么如何从中获取应用城市名称
  • 这是一个有点困难的任务,因为你必须做一些正则表达式的事情

标签: php google-maps reverse-geocoding


【解决方案1】:

这是解决方案,

<?php
    $lat = $_POST['lat'];
    $lng = $_POST['lng'];

    $url = 'http://maps.googleapis.com/maps/api/geocode/json?latlng='.$lat.','.$lng.'&sensor=false';
    $json = @file_get_contents($url);
    $data = json_decode($json);
    $status = $data->status;
    if($status=="OK") {
        //Get address from json data
        for ($j=0;$j<count($data->results[0]->address_components);$j++) {
            $cn=array($data->results[0]->address_components[$j]->types[0]);
            if(in_array("locality", $cn)) {
                $city= $data->results[0]->address_components[$j]->long_name;
            }
        }
     } else{
       echo 'Location Not Found';
     }
     //Print city 
     echo $city;

这解决了我的问题并且效果很好。主要部分是for循环,

for ($j=0;$j<count($data->results[0]->address_components);$j++) {
    $cn=array($data->results[0]->address_components[$j]->types[0]);
    if (in_array("locality", $cn)) {
        $city= $data->results[0]->address_components[$j]->long_name;
    }
}

希望这会有所帮助。

【讨论】:

    【解决方案2】:

    您可以在查询参数中指定result_type = locality,如下所示。

    有关过滤器的更多信息,您可以搜索Optional parameters in a reverse Geocoding request 文档。

    https://developers.google.com/maps/documentation/geocoding/intro#ReverseGeocoding

    【讨论】:

      猜你喜欢
      • 2012-05-07
      • 1970-01-01
      • 1970-01-01
      • 2016-02-10
      • 2022-01-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多