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

问题描述 投票:0回答:7

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

但是,我如何返回他们的坐标所在国家的名称?

javascript html geolocation
7个回答
38
投票

如果您只想要国家/地区,这里有一个更简单的方法,使用

ws.geonames.org
而不是 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);
        });
    });
}​

通常我会说使用 Google 服务意味着更高的可靠性,但由于最近有很多 Google 服务退役,因此考虑其他一些解决方案可能是个好主意。


顺便说一句,我使用我能找到的所有免费地理编码服务做了一些实验。一旦其中一个找到可接受的结果,它就会返回国家/地区和负责服务的名称。

您可以通过 JSFiddle 随意使用它:通过多个地理位置 webapi 延迟查找国家/地区代码


31
投票
    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;
}

我用的就是这个:)


2
投票

如果您在像我在 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);   
});

1
投票

注意使用此API需要设置'username'属性,否则会报错。

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

0
投票

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

0
投票

不使用 geoloc 或 IP 查找 API(仅免费供开发人员使用)

使用

Intl.DateTimeFormat().resolvedOptions().timeZone
和从
moment-timezone

中提取的文件

链接到演示(用户区域代码),您可以下载文件。


-1
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.