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

问题描述 投票:17回答:19

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

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

google-maps google-maps-api-3 geocoding reverse-geocoding postal-code
19个回答
1
投票

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

JAVASCRIPT

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

0
投票

总之,这是一项很大的努力。至少使用v2 API,我可以检索这些细节:

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

必须有一种更优雅的方式来检索单个address_components而无需通过您刚刚经历的循环jujitsu。


0
投票

这个简单的代码适合我

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

0
投票

使用Jquery

  • 您无法确定邮政编码存储在address_components数组中的哪个位置。有时在address_components.length - 1> pincode可能不存在。在“地址到latlng”地理编码中也是如此。
  • 您可以确定Postal代码将包含“postal_code”字符串。所以最好的方法就是检查一下。
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);
    }

0
投票
   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
投票

使用 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; }); ,可以通过一行代码轻松完成:

JSONPath

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

0
投票

现在看来,从宁静的API中获取它更好,只需尝试:

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

使用AJAX GET调用非常有效!

就像是:

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

0
投票

Romaine M. - 谢谢!如果您只需要在Google首次返回的结果中找到邮政编码,则只需执行2次循环:

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
投票

我认为不是依赖于索引,而是更好地检查组件内的地址类型键。我通过使用开关盒解决了这个问题。

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

2
投票
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!!');
        }
    });
}

1
投票
$.each(results[0].address_components,function(index,value){
    if(value.types[0] === "postal_code"){
        $('#postal_code').val(value.long_name);
    }
});

这对我来说似乎很有效,这与新的Google Maps API V3有关。如果这有助于任何人,写一个评论,我正在编写我的脚本,因为我们说...所以它可能会改变。


1
投票

在PHP中我使用此代码。它几乎在每种条件下都有效。

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

                }
            });
© www.soinside.com 2019 - 2024. All rights reserved.