使用Google Maps Javascript API V3反向地理编码获取邮政编码

23

我正在尝试在googlemaps视口中心发生更改时,使用邮政编码向我的数据库提交查询。我知道可以使用类似以下内容的反向地理编码来完成此操作:

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'];
  }
});
};

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


看起来我别无选择,只能迭代地址组件并搜索一个带有types[0] == 'postal_code'的地址组件? 有更好的方法吗? - Romaine M.
@RomainM 是的,我会假设除非您想手动从结果中解析它。 - KJYe.Name
是的,您必须遍历数组并查找其types数组中具有“postal_code”的元素,该元素可能位于最后、最前或任何位置。此外,哪个元素?您可能希望从results[0].address_componentsresults本身获取邮政编码:尝试两者并查看在您关心的区域中哪个更好用。一般来说,如果您关心具有完整地址的地点,则建议使用results[0].address_components,如果您关心严格包含您的latlng的邮政编码,则使用results - miguev
23个回答

1
使用 JSONPath,只需一行代码即可轻松完成:
var zip = $.results[0].address_components[?(@.types=="postal_code")].long_name;

1

Romaine M. - 谢谢!如果你只需要在 Google 的第一个返回结果中找到邮政编码,你可以只做两次循环:

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;
        }
    }
}

1
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。如果这能帮助到任何人,请留下评论,我正在编写我的脚本...所以它可能会改变。


1
在PHP中,我使用这段代码。几乎在任何情况下都可以正常工作。
$zip = $data["results"][3]["address_components"];
$zip = $index[0]["short_name"];

0
 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;
        });

0

使用Jquery

  • 你不能确定邮政编码存储在address_components数组的哪个位置。有时在address_components.length - 1 > pincode可能不存在。这在“地址到经纬度”地理编码中是正确的。
  • 你可以确定邮政编码将包含一个“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;

0
总之,这需要很多努力。至少使用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

一定有更优雅的方法来检索单个address_components,而不必像你刚才那样进行循环操作。


我希望你是对的,也许我只是不明白应该如何与对象交互。如果你看一下教程,很明显address_components是一个数组,由于Javascript没有关联数组,我能想到的唯一方法就是使用循环。 http://code.google.com/apis/maps/documentation/javascript/services.html#GeocodingResponses - Romaine M.

0

现在似乎更好的方法是从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 );
        });

0
//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;
            }
        }
    });

使用自动完成文本框,您可以获取所需的邮政地址。 - Ashu Ashutosh
1
请在您的答案中添加一些解释。这可能有助于原帖作者理解您在此发布的内容。 - Guillaume Racicot

0

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

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

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