使用 Google Maps Javascript API V3 反向地理编码检索邮政编码

发布于 2024-10-22 20:18:37 字数 465 浏览 6 评论 0原文

每当谷歌地图视口中心发生变化时,我都会尝试使用邮政编码向我的数据库提交查询。我知道这可以通过反向地理编码来完成,例如:

google.maps.event.addListener(map, 'center_changed', function(){
newCenter();
});
...
function newCenter(){
var newc = map.getCenter();
geocoder.geocode({'latLng': newc}, function(results, status){
if (status == google.maps.GeocoderStatus.OK) {
  var newzip = results[0].address_components['postal_code'];
  }
});
};

当然,这个代码实际上不起作用。所以我想知道我需要如何更改它才能从结果数组中提取邮政编码。 谢谢

I'm trying to submit a query using the postal code to my DB whenever the googlemaps viewport center changes. I know that this can be done with reverse geocoding with something like:

google.maps.event.addListener(map, 'center_changed', function(){
newCenter();
});
...
function newCenter(){
var newc = map.getCenter();
geocoder.geocode({'latLng': newc}, function(results, status){
if (status == google.maps.GeocoderStatus.OK) {
  var newzip = results[0].address_components['postal_code'];
  }
});
};

Of course, this code doesn't actually work. So I was wondering how I would need to change this in order to extract the postal code from the results array.
Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(23

如梦 2024-10-29 20:18:37

到目前为止我已经意识到,在大多数情况中,邮政编码始终是每个返回地址中的最后一个值,因此,如果您想检索第一个邮政编码(这是我的情况),您可以使用以下方法:

var address = results[0].address_components;
var zipcode = address[address.length - 1].long_name;

What I've realized so far is that in most cases the ZIPCODE is always the last value inside each returned address, so, if you want to retrieve the very first zipcode (this is my case), you can use the following approach:

var address = results[0].address_components;
var zipcode = address[address.length - 1].long_name;
尹雨沫 2024-10-29 20:18:37

您可以使用 underscore.js 库轻松完成此操作: http://documentcloud.github.com/underscore /#查找

_.find(results[0].address_components, function (ac) { return ac.types[0] == 'postal_code' }).short_name

You can do this pretty easily using the underscore.js libraray: http://documentcloud.github.com/underscore/#find

_.find(results[0].address_components, function (ac) { return ac.types[0] == 'postal_code' }).short_name
情绪 2024-10-29 20:18:37

使用 JQuery?

var searchAddressComponents = results[0].address_components,
    searchPostalCode="";

$.each(searchAddressComponents, function(){
    if(this.types[0]=="postal_code"){
        searchPostalCode=this.short_name;
    }
});

短名称或长名称将在上面工作
“searchPostalCode”变量将包含邮政(zip?)代码 IF
并且仅当您从 Google Maps API 获取地图时。

有时,您的查询不会得到“邮政编码”作为回报。

Using JQuery?

var searchAddressComponents = results[0].address_components,
    searchPostalCode="";

$.each(searchAddressComponents, function(){
    if(this.types[0]=="postal_code"){
        searchPostalCode=this.short_name;
    }
});

short_name or long_name will work above
the "searchPostalCode" var will contain the postal (zip?) code IF
and only IF you get one from the Google Maps API.

Sometimes you DO NOT get a "postal_code" in return for your query.

寄与心 2024-10-29 20:18:37

好吧,所以我明白了。该解决方案比我想要的要丑一些,而且我可能不需要最后一个 for 循环,但这里是其他需要从 address_components[] 中提取垃圾的人的代码。这是在地理编码器回调函数内部

// make sure to initialize i
for(i=0; i < results.length; i++){
            for(var j=0;j < results[i].address_components.length; j++){
                for(var k=0; k < results[i].address_components[j].types.length; k++){
                    if(results[i].address_components[j].types[k] == "postal_code"){
                        zipcode = results[i].address_components[j].short_name;
                    }
                }
            }
    }

Alright, so I got it. The solution is a little uglier than I'd like, and I probably don't need the last for loop, but here's the code for anyone else who needs to extract crap from address_components[]. This is inside the geocoder callback function

// make sure to initialize i
for(i=0; i < results.length; i++){
            for(var j=0;j < results[i].address_components.length; j++){
                for(var k=0; k < results[i].address_components[j].types.length; k++){
                    if(results[i].address_components[j].types[k] == "postal_code"){
                        zipcode = results[i].address_components[j].short_name;
                    }
                }
            }
    }
幻梦 2024-10-29 20:18:37
$.each(results[0].address_components,function(index,value){
    if(value.types[0] === "postal_code"){
        $('#postal_code').val(value.long_name);
    }
});
$.each(results[0].address_components,function(index,value){
    if(value.types[0] === "postal_code"){
        $('#postal_code').val(value.long_name);
    }
});
冷默言语 2024-10-29 20:18:37

您还可以使用 JavaScript .find 方法,类似于下划线 _.find 方法,但它是本机的,不需要额外的依赖。

const zip_code = results[0].address_components.find(addr => addr.types[0] === "postal_code").short_name;

You can also use JavaScript .find method which is similar to underscore _.find method but it is native and require no extra dependency.

const zip_code = results[0].address_components.find(addr => addr.types[0] === "postal_code").short_name;
番薯 2024-10-29 20:18:37

这只需要两个 for 循环。一旦我们发现第一个“类型”是“邮政编码”,“结果”数组就会更新。

然后它用新找到的数组集更新原始数组并再次循环。

            var i, j,
            result, types;

            // Loop through the Geocoder result set. Note that the results
            // array will change as this loop can self iterate.
            for (i = 0; i < results.length; i++) {

                result = results[i];

                types = result.types;

                for (j = 0; j < types.length; j++) {

                    if (types[j] === 'postal_code') {

                        // If we haven't found the "long_name" property,
                        // then we need to take this object and iterate through
                        // it again by setting it to our master loops array and 
                        // setting the index to -1
                        if (result.long_name === undefined) {
                            results = result.address_components;
                            i = -1;
                        }
                        // We've found it!
                        else {
                            postcode = result.long_name;
                        }

                        break;

                    }

                }

            }

This takes only two for loops. The "results" array gets updated once we found the first "type" to be "postal_code".

It then updates the original array with the newly found array set and loops again.

            var i, j,
            result, types;

            // Loop through the Geocoder result set. Note that the results
            // array will change as this loop can self iterate.
            for (i = 0; i < results.length; i++) {

                result = results[i];

                types = result.types;

                for (j = 0; j < types.length; j++) {

                    if (types[j] === 'postal_code') {

                        // If we haven't found the "long_name" property,
                        // then we need to take this object and iterate through
                        // it again by setting it to our master loops array and 
                        // setting the index to -1
                        if (result.long_name === undefined) {
                            results = result.address_components;
                            i = -1;
                        }
                        // We've found it!
                        else {
                            postcode = result.long_name;
                        }

                        break;

                    }

                }

            }
虫児飞 2024-10-29 20:18:37

您还可以使用此代码,此功能将有助于在单击按钮或 onblur 或 keyup 或 keydown 时获取 zip。

只需将地址传递给该函数即可。

使用 google api 并删除有效密钥和传感器选项,因为现在不需要。

function callZipAPI(addSearchZip)
{    
    var geocoder = new google.maps.Geocoder();
    var zipCode = null;

    geocoder.geocode({ 'address': addSearchZip }, function (results, status) {
        if (status == google.maps.GeocoderStatus.OK) {

            //var latitude = results[0].geometry.location.lat();
            //var longitude = results[0].geometry.location.lng();

            var addressComponent = results[0].address_components;            
            for (var x = 0 ; x < addressComponent.length; x++) {
                var chk = addressComponent[x];
                if (chk.types[0] == 'postal_code') {
                    zipCode = chk.long_name;
                }
            }
            if (zipCode) {
                alert(zipCode);
            }
            else {
                alert('No result found!!');
            }
        } else {            
            alert('Enter proper address!!');
        }
    });
}

You can also use this code, this function will help to get zip on button click or onblur or keyup or keydown.

Just pass the address to this function.

use google api with valid key and sensor option removed as it doesn't required now.

function callZipAPI(addSearchZip)
{    
    var geocoder = new google.maps.Geocoder();
    var zipCode = null;

    geocoder.geocode({ 'address': addSearchZip }, function (results, status) {
        if (status == google.maps.GeocoderStatus.OK) {

            //var latitude = results[0].geometry.location.lat();
            //var longitude = results[0].geometry.location.lng();

            var addressComponent = results[0].address_components;            
            for (var x = 0 ; x < addressComponent.length; x++) {
                var chk = addressComponent[x];
                if (chk.types[0] == 'postal_code') {
                    zipCode = chk.long_name;
                }
            }
            if (zipCode) {
                alert(zipCode);
            }
            else {
                alert('No result found!!');
            }
        } else {            
            alert('Enter proper address!!');
        }
    });
}
や莫失莫忘 2024-10-29 20:18:37

我使用此代码来获取“邮政编码”和“地点”,但您可以使用它来获取任何其他字段,只需更改类型的值:

JAVASCRIPT

var address = results[0].address_components;
var zipcode = '';
var locality = '';

for (var i = 0; i < address.length; i++) {
     if (address[i].types.includes("postal_code")){ zipcode = address[i].short_name; }    
     if (address[i].types.includes("locality")){ locality = address[i].short_name; }
}

I use this code to get "Postal code" and "locality", but you can use it to get any other field just changing the value of type:

JAVASCRIPT

var address = results[0].address_components;
var zipcode = '';
var locality = '';

for (var i = 0; i < address.length; i++) {
     if (address[i].types.includes("postal_code")){ zipcode = address[i].short_name; }    
     if (address[i].types.includes("locality")){ locality = address[i].short_name; }
}
九局 2024-10-29 20:18:37

我认为与其依赖索引,不如检查组件内部的地址类型键。我通过使用开关盒解决了这个问题。

      var address = '';
      var pin = '';
      var country = '';
      var state = '';
      var city = '';
      var streetNumber = '';
      var route ='';
      var place = autocomplete.getPlace(); 
      for (var i = 0; i < place.address_components.length; i++) {
        var component = place.address_components[i];
        var addressType = component.types[0];

        switch (addressType) {
            case 'street_number':
                streetNumber = component.long_name;
                break;
            case 'route':
                route = component.short_name;
                break;
            case 'locality':
                city = component.long_name;
                break;
            case 'administrative_area_level_1':
                state = component.long_name;
                break;
            case 'postal_code':
                pin = component.long_name;
                break;
            case 'country':
                country = component.long_name;
                break;
        }
       }

I think rather than depending on the index it better checks address type key inside the component. I solved this issue by using a switch case.

      var address = '';
      var pin = '';
      var country = '';
      var state = '';
      var city = '';
      var streetNumber = '';
      var route ='';
      var place = autocomplete.getPlace(); 
      for (var i = 0; i < place.address_components.length; i++) {
        var component = place.address_components[i];
        var addressType = component.types[0];

        switch (addressType) {
            case 'street_number':
                streetNumber = component.long_name;
                break;
            case 'route':
                route = component.short_name;
                break;
            case 'locality':
                city = component.long_name;
                break;
            case 'administrative_area_level_1':
                state = component.long_name;
                break;
            case 'postal_code':
                pin = component.long_name;
                break;
            case 'country':
                country = component.long_name;
                break;
        }
       }
冷…雨湿花 2024-10-29 20:18:37
places.getDetails( request_details, function(results_details, status){

                // Check if the Service is OK
                if (status == google.maps.places.PlacesServiceStatus.OK) {                  

                    places_postal           = results_details.address_components
                    places_phone            = results_details.formatted_phone_number
                    places_phone_int        = results_details.international_phone_number
                    places_format_address   = results_details.formatted_address
                    places_google_url       = results_details.url
                    places_website          = results_details.website
                    places_rating           = results_details.rating

                    for (var i = 0; i < places_postal.length; i++ ) {
                        if (places_postal[i].types == "postal_code"){
                            console.log(places_postal[i].long_name)
                        }
                    }

                }
            });

这对我来说似乎非常有效,这是与新的 Google Maps API V3 一起使用的。如果这对任何人有帮助,请写评论,我正在写我的脚本......所以它可能会改变。

places.getDetails( request_details, function(results_details, status){

                // Check if the Service is OK
                if (status == google.maps.places.PlacesServiceStatus.OK) {                  

                    places_postal           = results_details.address_components
                    places_phone            = results_details.formatted_phone_number
                    places_phone_int        = results_details.international_phone_number
                    places_format_address   = results_details.formatted_address
                    places_google_url       = results_details.url
                    places_website          = results_details.website
                    places_rating           = results_details.rating

                    for (var i = 0; i < places_postal.length; i++ ) {
                        if (places_postal[i].types == "postal_code"){
                            console.log(places_postal[i].long_name)
                        }
                    }

                }
            });

This seems to work very well for me, this is with the new Google Maps API V3. If this helps anyone, write a comment, i'm writing my script as we speak... so it might change.

再浓的妆也掩不了殇 2024-10-29 20:18:37

使用 JSONPath,只需一行代码即可轻松完成:

var zip = $.results[0].address_components[?(@.types=="postal_code")].long_name;

Using JSONPath, it's easily done with one line of code:

var zip = $.results[0].address_components[?(@.types=="postal_code")].long_name;
意犹 2024-10-29 20:18:37

在 PHP 中我使用这段代码。几乎在所有条件下它都有效。

$zip = $data["results"][3]["address_components"];
$zip = $index[0]["short_name"];

In PHP I use this code. Almost in every conditions it works.

$zip = $data["results"][3]["address_components"];
$zip = $index[0]["short_name"];
紫轩蝶泪 2024-10-29 20:18:37

罗曼·M.——谢谢!如果您只需要在 Google 返回的第一个结果中查找邮政编码,则只需执行 2 个循环:

for(var j=0;j < results[0].address_components.length; j++){
    for(var k=0; k < results[0].address_components[j].types.length; k++){
        if(results[0].address_components[j].types[k] == "postal_code"){
            zipcode = results[0].address_components[j].long_name;
        }
    }
}

Romaine M. — thanks! If you just need to find the postal code in the first returned result from Google, you can do just 2 loops:

for(var j=0;j < results[0].address_components.length; j++){
    for(var k=0; k < results[0].address_components[j].types.length; k++){
        if(results[0].address_components[j].types[k] == "postal_code"){
            zipcode = results[0].address_components[j].long_name;
        }
    }
}
寂寞花火° 2024-10-29 20:18:37

总而言之,这是一个很大的努力。至少使用 v2 API,我可以这样检索这些详细信息:

var place = response.Placemark[0];
var point = new GLatLng(place.Point.coordinates[1], place.Point.coordinates[0]);

myAddress = place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.Thoroughfare.ThoroughfareName

myCity = place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.LocalityName

myState = place.AddressDetails.Country.AdministrativeArea.AdministrativeAreaName

myZipCode = place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.PostalCode.PostalCodeNumber

必须有一种更优雅的方法来检索各个地址组件,而无需经历您刚刚经历的循环柔术。

In a word, that's a lot of effort. At least with the v2 API, I could retrieve those details thusly:

var place = response.Placemark[0];
var point = new GLatLng(place.Point.coordinates[1], place.Point.coordinates[0]);

myAddress = place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.Thoroughfare.ThoroughfareName

myCity = place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.LocalityName

myState = place.AddressDetails.Country.AdministrativeArea.AdministrativeAreaName

myZipCode = place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.PostalCode.PostalCodeNumber

There has got to be a more elegant way to retrieve individual address_components without going through the looping jujitsu you just went through.

唠甜嗑 2024-10-29 20:18:37

这个简单的代码对我有用

for (var i = 0; i < address.length; i++) {
        alert(address[i].types);
        if (address[i].types == "postal_code")
            $('#postalCode').val(address[i].long_name);
        if (address[i].types == "")
            $('#country').val(address[i].short_name);
    }

This simple code works for me

for (var i = 0; i < address.length; i++) {
        alert(address[i].types);
        if (address[i].types == "postal_code")
            $('#postalCode').val(address[i].long_name);
        if (address[i].types == "")
            $('#country').val(address[i].short_name);
    }
听不够的曲调 2024-10-29 20:18:37

使用 Jquery

  • 您无法确定邮政编码存储在 address_components 数组中的哪个位置。有时在address_components.length - 1 > pin 码可能不存在。这在“地址到 latlng”地理编码中是正确的。
  • 您可以确定邮政编码将包含“postal_code”字符串。所以最好的方法是检查一下。
   var postalObject = $.grep(results[0].address_components, function(n, i) {
                                    if (n.types[0] == "postal_code") {
                                        return n;
                                    } else {
                                        return null;
                                    }
                                });

                                $scope.query.Pincode = postalObject[0].long_name;

Using Jquery

  • You cant be sure in which location in the address_components array the postal code is stored. Sometimes in address_components.length - 1 > pincode may not be there. This is true in "Address to latlng" geocoding.
  • You can be sure that Postal code will contain a "postal_code" string. So best way is to check for that.
   var postalObject = $.grep(results[0].address_components, function(n, i) {
                                    if (n.types[0] == "postal_code") {
                                        return n;
                                    } else {
                                        return null;
                                    }
                                });

                                $scope.query.Pincode = postalObject[0].long_name;
末蓝 2024-10-29 20:18:37
 return $http.get('//maps.googleapis.com/maps/api/geocode/json', {
            params: {
                address: val,
                sensor: false
            }
        }).then(function (response) {
           var model= response.data.results.map(function (item) {
               // return item.address_components[0].short_name;
               var short_name;
             var st=  $.each(item.address_components, function (value, key) {
                    if (key.types[0] == "postal_code") {
                        short_name= key.short_name;
                    }
                });
             return short_name;

            });
                return model;
        });
 return $http.get('//maps.googleapis.com/maps/api/geocode/json', {
            params: {
                address: val,
                sensor: false
            }
        }).then(function (response) {
           var model= response.data.results.map(function (item) {
               // return item.address_components[0].short_name;
               var short_name;
             var st=  $.each(item.address_components, function (value, key) {
                    if (key.types[0] == "postal_code") {
                        short_name= key.short_name;
                    }
                });
             return short_name;

            });
                return model;
        });
初与友歌 2024-10-29 20:18:37
//autocomplete is the text box where u will get the suggestions for an address.

autocomplete.addListener('place_changed', function () {
//Place will get the selected place geocode and returns with the address              
//and marker information.
        var place = autocomplete.getPlace();
//To select just the zip code of complete address from marker, below loop //will help to find. Instead of y.long_name you can also use y.short_name. 
        var zipCode = null;
        for (var x = 0 ; x < place.address_components.length; x++) {
            var y = place.address_components[x];
            if (y.types[0] == 'postal_code') {
                zipCode = y.long_name;
            }
        }
    });
//autocomplete is the text box where u will get the suggestions for an address.

autocomplete.addListener('place_changed', function () {
//Place will get the selected place geocode and returns with the address              
//and marker information.
        var place = autocomplete.getPlace();
//To select just the zip code of complete address from marker, below loop //will help to find. Instead of y.long_name you can also use y.short_name. 
        var zipCode = null;
        for (var x = 0 ; x < place.address_components.length; x++) {
            var y = place.address_components[x];
            if (y.types[0] == 'postal_code') {
                zipCode = y.long_name;
            }
        }
    });
贱人配狗天长地久 2024-10-29 20:18:37

看来现在最好从restful API获取它,只需尝试:

https://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452&key=YOUR_KEY_HERE

使用 AJAX GET 调用效果非常好!

像这样的东西:

var your_api_key = "***";
var f_center_lat = 40.714224;
var f_center_lon = -73.961452;

$.ajax({ url: "https://maps.googleapis.com/maps/api/geocode/json?latlng="+f_center_lat+","+f_center_lon+"&key="+your_api_key,
            method: "GET"
        })
        .done(function( res ) { if (debug) console.log("Ajax result:"); console.log(res);
            var zipCode = null;
            var addressComponent = res.results[0].address_components;
            for (var x = 0 ; x < addressComponent.length; x++) {
                var chk = addressComponent[x];
                if (chk.types[0] == 'postal_code') {
                    zipCode = chk.long_name;
                }
            }
            if (zipCode) {
                //alert(zipCode);
                $(current_map_form + " #postalcode").val(zipCode);
            }
            else {
                //alert('No result found!!');
                if (debug) console.log("Zip/postal code not found for this map location.")
            }
        })
        .fail(function( jqXHR, textStatus ) {
            console.log( "Request failed (get postal code via geocoder rest api). Msg: " + textStatus );
        });

It seems that nowadays it's better to get it from the restful API, simply try:

https://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452&key=YOUR_KEY_HERE

Using an AJAX GET call works perfect!

Something like:

var your_api_key = "***";
var f_center_lat = 40.714224;
var f_center_lon = -73.961452;

$.ajax({ url: "https://maps.googleapis.com/maps/api/geocode/json?latlng="+f_center_lat+","+f_center_lon+"&key="+your_api_key,
            method: "GET"
        })
        .done(function( res ) { if (debug) console.log("Ajax result:"); console.log(res);
            var zipCode = null;
            var addressComponent = res.results[0].address_components;
            for (var x = 0 ; x < addressComponent.length; x++) {
                var chk = addressComponent[x];
                if (chk.types[0] == 'postal_code') {
                    zipCode = chk.long_name;
                }
            }
            if (zipCode) {
                //alert(zipCode);
                $(current_map_form + " #postalcode").val(zipCode);
            }
            else {
                //alert('No result found!!');
                if (debug) console.log("Zip/postal code not found for this map location.")
            }
        })
        .fail(function( jqXHR, textStatus ) {
            console.log( "Request failed (get postal code via geocoder rest api). Msg: " + textStatus );
        });
亚希 2024-10-29 20:18:37

据我所知, zip 是最后一个或最后一个之前的一个。
这就是为什么这是我的解决方案

const getZip = function (arr) {
  return (arr[arr.length - 1].types[0] === 'postal_code') ? arr[arr.length - 1].long_name : arr[arr.length - 2].long_name;
};
const zip = getZip(place.address_components);

As I got it zip is the last or the one that before last.
That why this is my solution

const getZip = function (arr) {
  return (arr[arr.length - 1].types[0] === 'postal_code') ? arr[arr.length - 1].long_name : arr[arr.length - 2].long_name;
};
const zip = getZip(place.address_components);
手心的海 2024-10-29 20:18:37

我认为这是最准确的解决方案:

zipCode: result.address_components.find(item => item.types[0] === 'postal_code').long_name;

i think this is the most accurate solution:

zipCode: result.address_components.find(item => item.types[0] === 'postal_code').long_name;
陈甜 2024-10-29 20:18:37

只需在所有类型中搜索 postal_code,找到即可返回。

const address_components = [{"long_name": "2b","short_name": "2b","types": ["street_number"]}, { "long_name": "Louis Schuermanstraat","short_name": "Louis Schuermanstraat", "types": ["route"]},{"long_name": "Gent","short_name": "Gent","types": ["locality","political" ]},{"long_name": "Oost-Vlaanderen","short_name": "OV","types": ["administrative_area_level_2","political"]},{"long_name": "Vlaanderen","short_name": "Vlaanderen","types": ["administrative_area_level_1","political"]},{"long_name": "België","short_name": "BE","types": ["country","political"]},{"long_name": "9040","short_name": "9040","types": ["postal_code"]}];
    
// address_components = results[0]address_components

console.log({
  'object': getByGeoType(address_components),
  'short_name': getByGeoType(address_components).short_name,
  'long_name': getByGeoType(address_components).long_name,
  'route': getByGeoType(address_components, ['route']).long_name,
  'place': getByGeoType(address_components, ['locality', 'political']).long_name
});


function getByGeoType(components, type = ['postal_code']) {
  let result = null;
  $.each(components,
    function() {
      if (this.types.some(r => type.indexOf(r) >= 0)) {
        result = this;
        return false;
      }
    });
  return result;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Just search for postal_code in all types, and return when found.

const address_components = [{"long_name": "2b","short_name": "2b","types": ["street_number"]}, { "long_name": "Louis Schuermanstraat","short_name": "Louis Schuermanstraat", "types": ["route"]},{"long_name": "Gent","short_name": "Gent","types": ["locality","political" ]},{"long_name": "Oost-Vlaanderen","short_name": "OV","types": ["administrative_area_level_2","political"]},{"long_name": "Vlaanderen","short_name": "Vlaanderen","types": ["administrative_area_level_1","political"]},{"long_name": "België","short_name": "BE","types": ["country","political"]},{"long_name": "9040","short_name": "9040","types": ["postal_code"]}];
    
// address_components = results[0]address_components

console.log({
  'object': getByGeoType(address_components),
  'short_name': getByGeoType(address_components).short_name,
  'long_name': getByGeoType(address_components).long_name,
  'route': getByGeoType(address_components, ['route']).long_name,
  'place': getByGeoType(address_components, ['locality', 'political']).long_name
});


function getByGeoType(components, type = ['postal_code']) {
  let result = null;
  $.each(components,
    function() {
      if (this.types.some(r => type.indexOf(r) >= 0)) {
        result = this;
        return false;
      }
    });
  return result;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文