Reputation: 13667
I’m using the Google Places API to find out what city somebody is in based on their ZIP code or post code.
For example, getting the city for the post code ‘SW1A 1AA’:
https://maps.googleapis.com/maps/api/place/autocomplete/json?key=[KEY]&input=sw1a%201aa
returns one prediction:
{
"predictions": [
{
...
"structured_formatting": {
"main_text": "SW1A 1AA",
"main_text_matched_substrings": [...],
"secondary_text": "London, UK"
},
"terms": [
{
"offset": 0,
"value": "London"
},
{
"offset": 7,
"value": "SW1A 1AA"
},
{
"offset": 17,
"value": "UK"
}
],
...
}
],
"status": "OK"
}
Which identifies that it is in London.
However, I want to know the city or country specifically. So I add in types=(country)
as instructed by the Google Places API docs:
https://maps.googleapis.com/maps/api/place/autocomplete/json?types=(country)&key=[KEY]&input=sw1a%201aa
this returns:
{
"predictions": [],
"status": "INVALID_REQUEST"
}
same if we try cities:
https://maps.googleapis.com/maps/api/place/autocomplete/json?types=(cities)&key=[KEY]&input=sw1a%201aa
{
"predictions": [],
"status": "ZERO_RESULTS"
}
I know there are quite a few questions similar to this already, but mostly around restricting an area. I don’t need or want to restrict an area, I just want to return only cities (or equivalents) as per Google’s documentation.
Does anybody know if I’m reading the documentation incorrectly? Is there a way to do this?
Upvotes: 0
Views: 1233
Reputation: 1140
If you want to use Google APIs to match postcodes with locations, then I would use the geocode API (note I think you will need a new API key)
https://maps.googleapis.com/maps/api/geocode/json?address=sw1a%201aa&key=APIKEY
types=(country)
is returning nothing because that is not what the flag is for in Autocomplete. You are forcing the API to consider your query as a country, which it is not, so it returns nothing. The correct query using a place type flag would be:
https://maps.googleapis.com/maps/api/place/autocomplete/json?key=APIKEY&input=sw1a%201aa&type=(regions)
In case you are interested, http://postcodes.io/ is another useful resource for translating postcodes to locations.
Upvotes: 2