Google Maps API может получить почтовый индекс, связанный с геолокацией. Однако, если вы находитесь где-то посреди джунглей, этот API не будет ничего возвращать, так как почтовый код сопоставлен с почтовыми адресами. В этом случае вам необходимо получить почтовый индекс ближайшего города.
Вы можете использовать этот метод для этого
//Reverse GeoCode position into Address and ZipCOde
function getZipCodeFromPosition(geocoder, map,latlng,userLocationInfoWindow) {
geocoder.geocode({'location': latlng}, function(result, status) {
if (status === 'OK') {
if (result[0]) {
console.log("GeoCode Results Found:"+JSON.stringify(result));
//Display Address
document.getElementById("address").textContent = "Address: " +result[0].formatted_address;
//Update Info Window on Server Map
userLocationInfoWindow.setPosition(latlng);
userLocationInfoWindow.setContent('<IMG BORDER="0" ALIGN="Left" SRC="https://media3.giphy.com/media/IkwH4WZWgdfpu/giphy.gif" style ="width:50px; height:50px"><h6 class ="pink-text">You Are Here</h4> <p class = "purple-text" style ="margin-left:30px;">'+result[0].formatted_address+'</p>');
userLocationInfoWindow.open(map);
map.setCenter(latlng);
//Try to Get Postal Code
var postal = null;
var city = null;
var state = null;
var country = null;
for(var i=0;i<result.length;++i){
if(result[i].types[0]=="postal_code"){
postal = result[i].long_name;
}
if(result[i].types[0]=="administrative_area_level_1"){
state = result[i].long_name;
}
if(result[i].types[0]=="locality"){
city = result[i].long_name;
}
if(result[i].types[0]=="country"){
country = result[i].long_name;
}
}
if (!postal) {
geocoder.geocode({ 'location': result[0].geometry.location }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
//Postal Code Not found, Try to get Postal code for City
var result=results[0].address_components;
for(var i=0;i<result.length;++i){
if(result[i].types[0]=="postal_code"){
postal = result[i].long_name;
}
}
if (!postal) {
//Postal Code Not found
document.getElementById("postal").textContent = "No Postal Code Found for this location";
}else
{
//Postal Code found
document.getElementById("postal").textContent = "Zip Code: "+postal;
}
}
});
} else
{
//Postal Code found
document.getElementById("postal").textContent = "Zip Code: "+postal;
}
console.log("STATE: " + state);
console.log("CITY: " + city);
console.log("COUNTRY: " + country);
} else {
window.alert('No results found');
}
} else {
window.alert('Geocoder failed due to: ' + status);
}
});
}
</script>
Рабочий пример
https://codepen.io/hiteshsahu/pen/gxQyQE?editors=1010
![enter image description here](https://i.stack.imgur.com/9NT4m.jpg)