If you have a location (and a Google Maps API v3 map), reverse geocode the location. Process through the returned records for the postal_code (see this SO post for an example).
// assumes comma separated coordinates in a input element
function codeLatLng() {
var input = document.getElementById('latlng').value;
var latlngStr = input.split(',', 2);
var lat = parseFloat(latlngStr[0]);
var lng = parseFloat(latlngStr[1]);
var latlng = new google.maps.LatLng(lat, lng);
geocoder.geocode({'latLng': latlng}, processRevGeocode);
}
// process the results
function processRevGeocode(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var result;
if (results.length > 1)
result = results[1];
else
result = results[0];
if (result.geometry.viewport)
map.fitBounds(result.geometry.viewport);
else if (result.geometry.bounds)
map.fitBounds(result.geometry.bounds);
else {
map.setCenter(result.geometry.location);
map.setZoom(11);
}
if (marker && marker.setMap) marker.setMap(null);
marker = new google.maps.Marker({
position: result.geometry.location,
map: map
});
infowindow.setContent(results[1].formatted_address);
infowindow.open(map, marker);
displayPostcode(results[0].address_components);
} else {
alert('Geocoder failed due to: ' + status);
}
}
// displays the resulting post code in a div
function displayPostcode(address) {
for (p = address.length-1; p >= 0; p--) {
if (address[p].types.indexOf("postal_code") != -1) {
document.getElementById('postcode').innerHTML= address[p].long_name;
}
}
}
Working example (displays a postcode from a geocoded address, reverse geocoded coordinates, or a click on the map)