json – 如何从V3 Google Maps API中提取邮政编码

前端之家收集整理的这篇文章主要介绍了json – 如何从V3 Google Maps API中提取邮政编码前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在使用以下内容从地理编码中获取纬度.
$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",{
      "long_name": "United States","short_name": "US","types": [ "country",{
      "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");

等等…

原文链接:https://www.f2er.com/js/151461.html

猜你在找的JavaScript相关文章