with the help of SA I have managed to get the lat, lng and the viewport bounds when a user wants to geolocate their current location.
Today, we had a person ask if we can also obtain the outcode ("postal_code_prefix") from the request. The is the first three/four digits of the UK postcode. I said this shouldn't be a problem and I can even see the outcode in the console. I read on this thread, Retrieving Postal Code with Google Maps Javascript API V3 Reverse Geocode, several good and bad answers and the most succinct one was the following:
for (i = 0; i < results.length; i++) {
for (var j = 0; j < results[i].address_components.length; j++) {
for (var k = 0; k < results[i].address_components[j].types.length; k++) {
if (results[i].address_components[j].types[k] == "postal_code_prefix") {
outcode = results[i].address_components[j].short_name;
} else if (results[i].address_components[j].types[k] == "postal_code") {
outcode = results[i].address_components[j].short_name;
}
}
}
}
I've tested this on 3 different computers and its worked perfectly. Can anyone see and drawbacks with this, or improvements? For example it would be ideal to have a one line solution, such as:
var outcode = results[1].address_components.postal_code_prefix.short_name();
I've searched the entire day and found no simple solution.
many thanks.