Javascript 如何使用 HTML5 地理定位查找用户所在的国家/地区?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6747833/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 23:00:32  来源:igfitidea点击:

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

javascripthtmlgeolocation

提问by Curt

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

我熟悉 HTML5 地理定位,用于返回用户位置的粗略坐标。

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

但是,如何返回其坐标所在的国家/地区的名称?

采纳答案by slandau

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

这就是我使用的:)

回答by hippietrail

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

如果你只想要这个国家,这里有一个更简单的方法,使用ws.geonames.org而不是谷歌:

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.

通常我会说使用 Google 服务意味着更高的可靠性,但是由于最近停用了这么多 Google 服务,因此查看其他一些解决方案可能是个好主意。



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

随意通过 JSFiddle 使用它:通过多个地理定位 webapis 延迟查找国家代码

回答by nilsi

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

如果您无法像我在 Chrome 中那样使用地理定位,那么我可以推荐这种替代方式(例如 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);   
});

回答by Kirill Shur

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

注意你需要设置'username'属性才能使用这个api,否则你会得到错误。

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

回答by Gabi Purcaru

You will need a Reverse Geocoderservice.

您将需要反向地理编码器服务。

回答by fentas

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

来自@hippietrail 的类似答案,但有另一个未注册的服务。

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