使用谷歌的逆地理编码获取街道、城市和国家信息

13

我试图从 Google 的 JSON 中获取 $street、$city 和 $country 字符串。对于我的家庭地址,它能够正常工作: http://maps.googleapis.com/maps/api/geocode/json?latlng=52.108662,6.307370&sensor=true

$url = "http://maps.googleapis.com/maps/api/geocode/json?latlng=".$lat.",".$lng."&sensor=true";
    $data = @file_get_contents($url);
    $jsondata = json_decode($data,true);
    if(is_array($jsondata) && $jsondata['status'] == "OK")
    {
          $city = $jsondata['results']['0']['address_components']['2']['long_name'];
          $country = $jsondata['results']['0']['address_components']['5']['long_name'];
          $street = $jsondata['results']['0']['address_components']['1']['long_name'];
    }

但是对于另一个包含更多数组数据的不同地址,例如:

http://maps.googleapis.com/maps/api/geocode/json?latlng=52.154184,6.199592&sensor=true

它不能正常工作,因为json数组中有更多数据,将省份看作了国家。

如何选择我需要的类型(long_name)?

  • 对于街道:使用 "types" : [ "route" ] 的 long_name
  • 对于城市:使用 "types" : [ "locality", "political" ] 的 long_name
  • 对于国家:使用 "types" : [ "country", "political" ] 的 long_name

来自geocode JSON的示例输出:

{
   "results" : [
      {
         "address_components" : [
            {
               "long_name" : "89",
               "short_name" : "89",
               "types" : [ "street_number" ]
            },
            {
               "long_name" : "Wieck De",
               "short_name" : "Wieck De",
               "types" : [ "establishment" ]
            },
            {
               "long_name" : "Industrieweg",
               "short_name" : "Industrieweg",
               "types" : [ "route" ]
            },
            {
               "long_name" : "Zutphen",
               "short_name" : "Zutphen",
               "types" : [ "locality", "political" ]
            },
            {
               "long_name" : "Zutphen",
               "short_name" : "Zutphen",
               "types" : [ "administrative_area_level_2", "political" ]
            },
            {
               "long_name" : "Gelderland",
               "short_name" : "GE",
               "types" : [ "administrative_area_level_1", "political" ]
            },
            {
               "long_name" : "Nederland",
               "short_name" : "NL",
               "types" : [ "country", "political" ]
            },
            {
               "long_name" : "7202 CA",
               "short_name" : "7202 CA",
               "types" : [ "postal_code" ]
            }

我想我自己修好了,这是我的代码:

// street
foreach ($jsondata["results"] as $result) {
    foreach ($result["address_components"] as $address) {
        if (in_array("route", $address["types"])) {
            $street = $address["long_name"];
        }
    }
}
// city
foreach ($jsondata["results"] as $result) {
    foreach ($result["address_components"] as $address) {
        if (in_array("locality", $address["types"])) {
            $city = $address["long_name"];
        }
    }
}
// country
foreach ($jsondata["results"] as $result) {
    foreach ($result["address_components"] as $address) {
        if (in_array("country", $address["types"])) {
            $country = $address["long_name"];
        }
    }
}
4个回答

10
你可以将数据转换成关联数组并像这样处理它。
 $data = array();
 foreach($jsondata['results']['0']['address_components'] as $element){
     $data[ implode(' ',$element['types']) ] = $element['long_name'];
 }
 print_r($data);

 echo 'route: ' . $data['route'] . "\n";
 echo 'country: ' . $data['country political'];

3
您的代码很好,但是在使用重复的foreach循环之前,使用一个foreach内部的switch是否更好呢?以下是我解析完全相同数组的方法:
  $location = array();

  foreach ($result['address_components'] as $component) {

    switch ($component['types']) {
      case in_array('street_number', $component['types']):
        $location['street_number'] = $component['long_name'];
        break;
      case in_array('route', $component['types']):
        $location['street'] = $component['long_name'];
        break;
      case in_array('sublocality', $component['types']):
        $location['sublocality'] = $component['long_name'];
        break;
      case in_array('locality', $component['types']):
        $location['locality'] = $component['long_name'];
        break;
      case in_array('administrative_area_level_2', $component['types']):
        $location['admin_2'] = $component['long_name'];
        break;
      case in_array('administrative_area_level_1', $component['types']):
        $location['admin_1'] = $component['long_name'];
        break;
      case in_array('postal_code', $component['types']):
        $location['postal_code'] = $component['long_name'];
        break;
      case in_array('country', $component['types']):
        $location['country'] = $component['long_name'];
        break;
    }

  }

这样做不行,因为第一个组件是最可靠的,只需制作casesif循环即可。 - Chibueze Opata

2

如果您使用邮政编码查找地址,而我最近使用Google MAP API生成了街道、城市和国家,代码如下:

$search_code = urlencode($postcode);
        $url = 'http://maps.googleapis.com/maps/api/geocode/json?address=' . $search_code . '&sensor=false';
        $json = json_decode(file_get_contents($url));
        if($json->results == []){
            return '';
        }
        $lat = $json->results[0]->geometry->location->lat;
        $lng = $json->results[0]->geometry->location->lng;

        //Now build the actual lookup
        $address_url = 'http://maps.googleapis.com/maps/api/geocode/json?latlng=' . $lat . ',' . $lng . '&sensor=false';
        $address_json = json_decode(file_get_contents($address_url));

        $address_data = $address_json->results[0]->address_components;
        //return $address_data = $address_json->results[0]->formatted_address;

        $street = str_replace('Dr', 'Drive', $address_data[1]->long_name);
        $town = $address_data[2]->long_name;
        $county = $address_data[3]->long_name;

        return $street.', '. $town. ', '.$county;

0

看起来需要一个类似JMESpath http://jmespath.org/的集合解析器来完成这项工作。

给定数组

{
  "locations": [
    {"name": "Seattle", "state": "WA"},
    {"name": "New York", "state": "NY"},
    {"name": "Bellevue", "state": "WA"},
    {"name": "Olympia", "state": "WA"}
  ]
}

一个JMESPath查询:

locations[?state == 'WA'].name | sort(@) | {WashingtonCities: join(', ', @)}

返回结果为:

{
  "WashingtonCities": "Bellevue, Olympia, Seattle"
}

你需要根据你的情况进行重写,但是你可以了解到这种语言有多么强大。你可以使用composer来安装PHP的JMESPath实现。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接