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

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

Leave a Comment