I am using the geocoding API passing postal codes (GB mainly) to validate if the postal code is valid or not (using the address_components and types where if it returns "postal_code" I take that it is valid) but I have found 2 issues.
Also is this the best method with Google Maps to validate a postal code?
"address_components": [ { "long_name": "GU2 7UP", "short_name": "GU2 7UP", "types": [ "postal_code" ] },
"address_components": [ { "long_name": "OL1 1NY", "short_name": "OL1 1NY", "types": [ "postal_code" ] },
For both issues I was expecting that would give me a response without a postal code match and would state the below as it does for another invalid postal code of ME4 4QQ
"address_components": [
{
"long_name": "United Kingdom",
"short_name": "GB",
"types": [
"country",
"political"
]
}
Thanks
Component filtering is probably a better approach, at least it will prevent false positive results, e.g. returning GU2 7UP when requesting GU2 7YP:
https://maps.googleapis.com/maps/api/geocode/json?components=country:GB|postal_code:GU2%207YP returns ZERO_RESULTS
because the components
parameter enforces an exact match on postal_code:GU2%207YP
Whether a result is returned or not depends mostly on Google Maps data being accurate and up to date.
Another option could be using the new Address Validation API which broadly speaking provides 2 different "results":
address
: how much of the input is confirmed to be (part of) a valid postal addressgeocode
: where would Google Maps locate the input (may or may not match the address
).More details in Understand the validation response.
As an example, the Address Validation Demo returns an address
that essentially says "yes, GU2 7YP is a valid UK postal code", but the geocode
returned is in fact GU2 7UP (Place ID: ChIJm7gwBcLQdUgRSfAroiN7KYw) because that's the (closet) one available.