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

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?


Solution 1:

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

Solution 2:

    var geocoder = new google.maps.Geocoder();
    geocoder.geocode({'latLng': <YOURLATLNGRESPONSEFROMGEO>}, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                if (results[0]) {
                    var loc = getCountry(results);
                }
            }
        });

    function getCountry(results)
    {
        for (var i = 0; i < results[0].address_components.length; i++)
        {
        var shortname = results[0].address_components[i].short_name;
        var longname = results[0].address_components[i].long_name;
        var type = results[0].address_components[i].types;
        if (type.indexOf("country") != -1)
        {
            if (!isNullOrWhitespace(shortname))
            {
                return shortname;
            }
            else
            {
                return longname;
            }
        }
    }

}

function isNullOrWhitespace(text) {
    if (text == null) {
        return true;
    }
    return text.replace(/\s/gi, '').length < 1;
}

This is what I use :)