City/Country text field validation
I need to keep track of the users lat/lng/city/country for my application with the following two requirements:
1) Get the users lat/lng/city/country automatically. (This is easy, I can use the ip or if they have a browser that supports geolocation, even better).
2) The user is allowed to customize this location (maybe the ip address lookup didn't give an accurate city). The location is a freeform text field (not a dropdown). When the user enters a new location it should be validated against available cities/countries. If it validates against any one of them, select it and then retrieve the latlng for the new location. (This is what I'm having trouble with)
Also to clarify, this is a Rails 3 app using MongoDB. I am looking for either a single API or database that would allow me to do both (1) and (2). Has anyone done anything similar? Looking for some ideas as to how others have done this.
Your question isn't entirely clear as to what problem you are having. In general terms, I would do it like this:
- have a Location model that stores location name and coordinates
- when the user enters a location, send an Ajax request to look it up
- if it's found, set the location in the session
- if it isn't found, return a list of similarly named locations (in case there was a typo) and let the user choose one or stick to their input
- when they are done with the input, insert a new location if required and store User.location_id.
You could use Google's Geocoding API to look up the coordinates of unknown locations.
I would recommend the Geokit Gem, it does a very nice job of providing a front end for several Geocoding APIs. I highly recommend sticking with Yahoo or Google, just for sheer data integrity issues.
There is a rails plugin, that adds some nice helpers to Activerecord. At the moment the main project is not rails 3 compatible, but there is at least one fork that has updated for rails 3.