I need a list of countries, states & cities based on a collection of lat/long values I have. I need to store this information in a manner that hierarchy is preserve and without duplicates (e.g. "USA" and "United States" and "United States of America" are the same country; I only want one instance of this country in my database).
Is this possible to do with Google Map API?
I wrote this function that extracts what you are looking for based on the
address_components
returned from the gmaps API. This is the city (for example).Change
locality
toadministrative_area_level_1
for the State etc.In my js code I am using like so:
Will return:
Waltham, MA
@Szkíta Had a great solution by creating a function that gets the address parts in a named array. Here is a compiled solution for those who want to use plain JavaScript.
Function to convert results to the named array:
Geocode the LAT/LNG values:
I used this question as a starting point for my own solution. Thought it was appropriate to contribute my code back since its smaller than tabacitu's
Dependencies:
Code:
What you are looking for is called reverse geocoding. Google provides a server-side reverse geocoding service through the Google Geocoding API, which you should be able to use for your project.
This is how a response to the following request would look like:
Response:
You can also opt to receive the response in xml instead of json, by simply substituting json for xml in the request URI:
As far as I know, Google will also return the same name for address components, especially for high-level names like country names and city names. Nevertheless, keep in mind that while the results are very accurate for most applications, you could still find the occasional spelling mistake or ambiguous result.
I found the GeoCoder javascript a little buggy when I included it in my jsp files.
You can also try this:
I've created a small mapper function:
It's a solution for Angular 4 but I think you'll get the idea.
Usage:
This way the
address
object will be something like this:Hope it helps!