简体   繁体   中英

get address and zipcode with longitude and latitude in google map

in google map api, i want to extract map center latitude and longitude and get address of there like a zipcode. this is possible to get zipcode ?
i use this for this purpose

var lat = -24.448674;
        var lng = 135.684569;
        var geocoder = new google.maps.Geocoder();
        var latlng = new google.maps.LatLng(lat, lng);
        geocoder.geocode({'latLng': latlng}, function(results, status)
        {
            if (status == google.maps.GeocoderStatus.OK)
            {
                if (results[1]) {
                    alert(results[1].formatted_address);
                } else {
                    alert("No results found");
                }
            }
            else
            {
                alert("Geocoder failed due to: " + status);
            }
        });

but in above code i can't get zipcode and get postal code!
https://developers.google.com/maps/documentation/geocoding/

You can get postal code searching for postal_code type:

    if (status == google.maps.GeocoderStatus.OK) {
        if (results[0]) {
            for (var i = 0; i < results[0].address_components.length; i++) {
                var types = results[0].address_components[i].types;

                for (var typeIdx = 0; typeIdx < types.length; typeIdx++) {
                    if (types[typeIdx] == 'postal_code') {
                        //console.log(results[0].address_components[i].long_name);
                        console.log(results[0].address_components[i].short_name);
                    }
                }
            }
        } else {
            console.log("No results found");
        }
    }

As far as I'm aware, you've answered your own question here. The 'Postal Code' is the generic name given to the mailing address identifier used in each country. In the case of the US this would be the 'Zip Code', in the UK the 'Post Code' etc.

From the documentation you linked:

postal_code indicates a postal code as used to address postal mail within the country.

The field under Postal Code is likely what you're looking for, don't let the naming convention fool you. It would be unnecessary work on the part of Google to rename the field for each country's possible variations.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM