json - 如何从 V3 Google map API 中提取邮政编码

标签 json google-maps

我正在使用以下内容从地理编码中获取 lat-lng ..

  $latitude = $output->results[0]->geometry->location->lat;
  $longitude = $output->results[0]->geometry->location->lng;

如何从...中提取邮政编码
{
  "status": "OK",
  "results": [ {
    "types": [ "street_address" ],
    "formatted_address": "1600 Amphitheatre Pkwy, Mountain View, CA 94043, USA",
    "address_components": [ {
      "long_name": "1600",
      "short_name": "1600",
      "types": [ "street_number" ]
    }, {
      "long_name": "Amphitheatre Pkwy",
      "short_name": "Amphitheatre Pkwy",
      "types": [ "route" ]
    }, {
      "long_name": "Mountain View",
      "short_name": "Mountain View",
      "types": [ "locality", "political" ]
    }, {
      "long_name": "California",
      "short_name": "CA",
      "types": [ "administrative_area_level_1", "political" ]
    }, {
      "long_name": "United States",
      "short_name": "US",
      "types": [ "country", "political" ]
    }, {
      "long_name": "94043",
      "short_name": "94043",
      "types": [ "postal_code" ]
    } ],
    "geometry": {
      "location": {
        "lat": 37.4219720,
        "lng": -122.0841430
      },
      "location_type": "ROOFTOP",
      "viewport": {
        "southwest": {
          "lat": 37.4188244,
          "lng": -122.0872906
        },
        "northeast": {
          "lat": 37.4251196,
          "lng": -122.0809954
        }
      }
    }
  } ]
}

最佳答案

您可以使用以下函数来提取任何地址组件:

function extractFromAdress(components, type){
    for (var i=0; i<components.length; i++)
        for (var j=0; j<components[i].types.length; j++)
            if (components[i].types[j]==type) return components[i].long_name;
    return "";
}

要提取您调用的邮政编码:
extractFromAdress(results[0].address_components, "postal_code");

但您也可以获得其他有趣的信息,例如:
extractFromAdress(results[0].address_components, "route");
extractFromAdress(results[0].address_components, "locality");
extractFromAdress(results[0].address_components, "country");

ETC...

关于json - 如何从 V3 Google map API 中提取邮政编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8150132/

相关文章:

c# - Json反序列化异常

json - 安装 json 时出错 : Failed to build gem native extension

jquery - 从 JSON 中提取多个数据集

java - 带有 Jackson token 流的 JSON 中的非常长的字符串(> 1 gig)

javascript - map 在第一次打开页面时不加载,重新加载后即可工作

javascript - 将 XML 数据加载到 Google map 中?

javascript - 如何在 json 对象中访问此键? (javascript)

android - Google Play 服务 - 包含 dex 错误

javascript - 单击 InfoWindow Typescript Angular2

javascript - Google Maps API v3 - 在链接点击时从标记绘制路线