Search code examples
javascripthtmlgeolocationlocationgoogle-geolocation

What is the best way to get a user's city?


I understand that this looks like a duplicate question but my problem is slightly different and nothing already posted helped me.

I need to detect the user's city. I'm currently just encoding the user's IP to city name using some third-party API. But that's really inaccurate (consider my country Nepal where almost all places are shown as the capital city).

I tried with HTML5's geo-location API but that just gives me the user's geo coordinates. I tried using Google's Geocoding API but I didn't get a consistent format of the results (probably because of difference in how addresses are written in different countries). I mean in the resulting JSON object, for addresses in the US, the fifth object gives the city name while for addresses in the UK, it's the fourth object and something else for addresses in India.

For example,

See

http://maps.googleapis.com/maps/api/geocode/json?latlng=51.441944,%20-0.945556&sensor=true

vs

http://maps.googleapis.com/maps/api/geocode/json?latlng=42.155101995,-71.10080&sensor=true.

This inconsistency makes it really difficult for my code to parse the city name from the result JSON.

The same problem is brought up in the comments of How to get city from coordinates? but no solution.

Ideally, I'd love to somehow map a user's geocoordinates to his/her city name (how?) and use IP based detection only as a fallback. However, the only solution I found for the coordinates-to-name mapping (Google API) isn't working in my case.

Thanks!


Solution

  • I think you're entering this problem with an invalid hypothesis: that all geocoordinates are bounded by a city. The best you may be able to do is a much larger administrative area (e.g., a province).

    On parsing Google Maps API's geocoding responses: the types key contains an array of address components that are applicable to the corresponding value. These types are well-defined in the Geocoding API "Types" section. Moreover, these types are universal and do not vary from country to country.

    You'll need to substitute appropriate fallbacks, but it looks like locality is the type you want to reference. In the case of coordinates not being bound by a city, administrative_area_level_2 is possible next-best value to reference.