开发者

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

开发者 https://www.devze.com 2023-03-21 03:02 出处:网络
I\'m familiar with HTML5 geolocation for returning rough coordinates of the user’s location. However, how can I return th开发者_JAVA技巧e name of the country that their coordinates are in?If you jus

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

However, how can I return th开发者_JAVA技巧e name of the country that their coordinates are in?


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


    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 :)


If you have problem getting geolocation to work like I had in Chrome, then I can recommend this alternative way (example with jQuery):

$.getJSON("https://freegeoip.net/json/", function(data) {
    const countryCode = data.country_code;
    const countryName = data.country_name;
    const ip = data.ip;
    const timezone = data.time_zone;
    const latitude = data.latitude;
    const longitude = data.longitude;

    alert("Country Code: " + countryCode);
    alert("Country Name: " + countryName);
    alert("IP: " + ip); 
    alert("Time Zone: " + timezone);
    alert("Latitude: " + latitude);
    alert("Longitude: " + longitude);   
});


pay attention you need set 'username' property for using this api,otherwise you'll get error.

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

            }, 1000);


Similar answer as from @hippietrail but with another service without registration.

if ( navigator.geolocation ) {
  navigator.geolocation.getCurrentPosition(function(position) {

  $.ajax('http://www.datasciencetoolkit.org/coordinates2politics/'
    + position.coords.latitude + ','
    + position.coords.longitude, {dataType: 'jsonp'})
  .done(function(data, textStatus, jqXHR) {
    if ( textStatus === 'success' ) {
      var country = data[0].politics[0].name
      alert(country)
    }
  })
}


You will need a Reverse Geocoder service.

0

精彩评论

暂无评论...
验证码 换一张
取 消