Search code examples
geolocation

How to get user's geolocation?


On many sites I saw printed out my current city where I am (eg "Hello to Berlin."). How they do that? What everything is needed for that? I guess the main part is here javascript, but what everything I need for implementing something like this to my own app? (or is there some gem for Rails?)

Also, I would like to ask for one thing yet - I am interesting in the list of states (usually in select box), where user select his state (let's say Germany), according to the state value are in another select displayed all regions in Germany and after choosing a region are displayed respective cities in the selected region.

Is possible anywhere to obtain this huge database of states/cities/regions? Would be interesting to have something similar in our app, but I don't know, where those lists get...


Solution

  • You need a browser which supports the geolocation api to obtain the location of the user (however, you need the user's consent (an example here) to do so (most newer browsers support that feature, including IE9+ and most mobile OS'es browsers, including Windows Phone 7.5+).

    all you have to do then is use JavaScript to obtain the location:

    if (window.navigator.geolocation) {
        var failure, success;
        success = function(position) {
          console.log(position);
        };
        failure = function(message) {
          alert('Cannot retrieve location!');
        };
        navigator.geolocation.getCurrentPosition(success, failure, {
          maximumAge: Infinity,
          timeout: 5000
        });
    }
    

    The positionobject will hold latitude and longitude of the user's position (however this can be highly inaccurate in less densely populated areas on desktop browsers, as they do not have a GPS device built in). To explain further: Here in Leipzig in get an accuracy of about 300 meters on a desktop computer - i get an accuracy of about 30 meters with my cell phone's GPS device.

    You can then go on and use the coordinates with the Google Maps API (see here for reverse geocoding) to lookup the location of the user. There are a few gems for Rails, if you want. I never felt the need to use them, but some people seem to like them.

    As for a list of countries/cities, we used the data obtainable from Geonames once in a project, but we needed to convert it for our needs first.