Google地图地理编码结果顺序



我正在使用Google Maps地理编码API发送部分地址并接收完整的地址信息。

Google的API在基于其能够匹配的部分地址的数据返回结果的方式上不一致,特别是" address_components"字段中的对象数(ex:有时它将包括'commission_area_lea_level_2',在这种情况下,"国王县")。

我有没有办法使用"类型"字段作为标识符检索特定的" address_component"数据?否则,似乎我必须执行一系列手动检查以确定Google返回了多少个地址_COMPONENTS。

我感兴趣的JSON响应的部分是:

{
"results":[  
  {  
     "address_components":[  
        {  
           "long_name":"125",
           "short_name":"125",
           "types":[  
              "street_number"
           ]
        },
        {  
           "long_name":"Court Street",
           "short_name":"Court St",
           "types":[  
              "route"
           ]
        },
        {  
           "long_name":"Brooklyn",
           "short_name":"Brooklyn",
           "types":[  
              "political",
              "sublocality",
              "sublocality_level_1"
           ]
        },
        {  
           "long_name":"Kings County",
           "short_name":"Kings County",
           "types":[  
              "administrative_area_level_2",
              "political"
           ]
        },
        {  
           "long_name":"New York",
           "short_name":"NY",
           "types":[  
              "administrative_area_level_1",
              "political"
           ]
        },
        {  
           "long_name":"United States",
           "short_name":"US",
           "types":[  
              "country",
              "political"
           ]
        },
        {  
           "long_name":"11201",
           "short_name":"11201",
           "types":[  
              "postal_code"
           ]
        }
     ],

非常感谢。

<?php
$addr = json_decode('{json here..}', true);

/**
 * @param string $name
 * @param string $type
 * @param array  $from
 * @return string|array|null
 */
function getByType($name, $type, array $from)
{
    foreach($from as $values) {
        if (in_array($type, $values['types'])) {
            return $values[$name] ?: $values;
        }
    }
    return null;
}

var_dump(getByType('long_name', 'route', $addr['results'][0]['address_components']));

3v4l这里

您可以编写一个函数来检索给定类型的组件对象。这样的东西:

$components = ...; // The JSON decoded "address_components" array
/**
 * Get a component by type.
 *
 * @param  {string} $type The component type. E.g. 'street_number'.
 * @return {null|object} The desired component or null in case there's no
 *                       component for the given type.
 */
$componentByType = function ($type) use ($components) {
    $found = array_filter($components, function ($component) use ($type) {
        return in_array($type, $component->types);
    });
    return reset($found);
};

使用问题的回答,以下代码...

$component = $componentByType('route');
echo $component->long_name;

...将输出:

法院街

最新更新