问题
We use the Google Maps API, and when a user inputs a 5 digit ZIP code, the results are correct the vast majority of the time; it treats the input as a ZIP code and returns results based on that location.
The problem that has come to our attention is that queries for certain ZIP codes (42025 is our prime example) does NOT return the expected results (Benton, KY). The API call actually returns "status":"ZERO_RESULTS". A similar search on maps.google.com will sometimes produce a positive result, but only if Benton, KY consumes a large portion of the viewport already. A workaround is to add the term "zip" in the query string.
My investigation has shown that the failed results appear to be using the 5 digit string as if a street address, which find nothing. A query for "42020" ends up showing some address near Washington D.C., for example.
Has anyone faced this issue? Any suggestions for how to address this?
回答1:
I would suggest using a component filtering in your Geocoder requests in order to obtain postal codes.
Your requests will be rewritten as
https://maps.googleapis.com/maps/api/geocode/json?components=postal_code%3A42025%7Ccountry%3AUS&key=YOUR_API_KEY
https://maps.googleapis.com/maps/api/geocode/json?components=postal_code%3A42020%7Ccountry%3AUS&key=YOUR_API_KEY
Both requests return expected results to me. You can also see it in the Geocoder tool:
https://google-developers.appspot.com/maps/documentation/utils/geocoder/#q%3D%26options%3Dtrue%26in_country%3DUS%26in_postal_code%3D42025
https://google-developers.appspot.com/maps/documentation/utils/geocoder/#q%3D%26options%3Dtrue%26in_country%3DUS%26in_postal_code%3D42020
I hope this helps!
来源:https://stackoverflow.com/questions/52501111/google-maps-api-query-with-only-zip-code-provides-incorrect-results