How to get user's geolocation?

2020-02-29 03:38发布

问题:

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...

回答1:

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.



回答2:

I've found getCurrentPosition() to often be inaccurate since it doesn't spend a lot of time waiting on the GPS to acquire a good accuracy. I wrote a small piece of JavaScript that mimics getCurrentPosition() but actually uses watch position and monitors the results coming back until they are better accuracy.

Here's how it looks:

navigator.geolocation.getAccurateCurrentPosition(onSuccess, onError, {desiredAccuracy:20, maxWait:15000});

Code is here - https://github.com/gwilson/getAccurateCurrentPosition



回答3:

Correc syntax would be :

navigator.geolocation.getCurrentPosition(successCallBack, failureCallBack);

Use :

    navigator.geolocation.getCurrentPosition(
        function(position){
            var latitude  = position.coords.latitude;
            var longitude = position.coords.longitude;
            console.log("Latitude : "+latitude+" Longitude : "+longitude);
        },
        function(){
            alert("Geo Location not supported");
        }
    );         


回答4:

Internet Service Providers buy up big chunks of IP addresses, so what you're most likely seeing is a backtrace your IP to a known ISP. They have a database with ISP's and their location in the world, so they can try to see where you're from. You could try to use a site like http://www.ipaddresslocation.org/ to do your work. If you look around, there is bound to be a site that lets you enter an IP and get a location, so you just send a POST request to that site with your visitor's IP and scrape the location from the response.

Alternatively you could try to look for an ISP database that has location and what chunks of the IP range they have been allocated. You could probably find one for money, but a free one might be harder to find. Alternatively, check out this free database http://www.maxmind.com/app/geolite



回答5:

Here is an another api to find out the location in PHP,

http://ipinfodb.com/ip_location_api.php



回答6:

I have been using geoip.maxmind.com for quite a while and it works 100%. It can be accessed via HTTP requests.



回答7:

If you prefer to use ES6 and promises here is another version

function getPositionPromised() {
  function successCb(cb) {
    return position => cb(position);
  }

  function errorCb(cb) {
    return () => cb('Could not retrieve geolocation');
  }

  return new Promise((resolve, reject) => {
    if (window.navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(successCb(resolve), errorCb(reject));
    } else {
      return reject('No geolocation support');
    }
  })
}

And you can use it like this:

getPositionPromised()
  .then(position => {/*do something with position*/})
  .catch(() => {/*something went wrong*/})


标签: geolocation