How can I find a user’s country using HTML5 geolocation?

Curt picture Curt · Jul 19, 2011 · Viewed 44.1k times · Source

I'm familiar with HTML5 geolocation for returning rough coordinates of the user’s location.

However, how can I return the name of the country that their coordinates are in?

Answer

hippietrail picture hippietrail · Aug 2, 2012

If you just want the country, here's a much simpler approach using ws.geonames.org rather than Google:

if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) {
        $.getJSON('http://ws.geonames.org/countryCode', {
            lat: position.coords.latitude,
            lng: position.coords.longitude,
            type: 'JSON'
        }, function(result) {
            alert(result.countryName);
        });
    });
}​

Normally I would say that using a Google service would mean greater reliability, but with so many Google services being retired lately it's probably a good idea to look at some other solutions.


By the way, I did some experiments using all the free geocoding services I could find. It returns the country and the name of the service responsible as soon as one of them finds an acceptable result.

Feel free to play with it via JSFiddle: Deferred look up country code via multiple geolocation webapis