【问题标题】:How can I find a user’s country using HTML5 geolocation?如何使用 HTML5 地理位置找到用户所在的国家/地区?
【发布时间】:2011-10-08 12:52:36
【问题描述】:

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

但是,我怎样才能返回他们坐标所在国家的名称?

【问题讨论】:

标签: javascript html geolocation


【解决方案1】:

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

【讨论】:

  • 简洁的解决方案,行数很少!它也不需要用户交互来找出他的位置。
  • 请注意,截至 2020 年,这不起作用。服务现在是高级的(尽管有一个有限的免费帐户)。
  • 它重定向到ipstack.com,有定价。
【解决方案2】:

注意你需要设置'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);

【讨论】:

    【解决方案3】:

    来自@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)
        }
      })
    }
    

    【讨论】:

      【解决方案4】:

      如果您只想要国家/地区,这里有一个更简单的方法,使用 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 随意使用它:Deferred look up country code via multiple geolocation webapis

      【讨论】:

      • 我真的很喜欢这个答案的简单性......而且它的答案更开放;)
      • 屏蔽谷歌的国家的最佳答案:)
      • 错误:为每次调用添加用户名,以便地理名称能够识别调用应用程序并计算积分
      • @zloctb:是的,geonames 似乎已将其网络服务更改为现在需要注册用户名:“参数'用户名'需要与每个请求一起传递。您的应用程序的用户名可以注册@987654323 @. 然后您将收到一封带有确认链接的电子邮件,在您确认电子邮件后,您可以在your account page"上启用您的网络服务帐户"
      • ws.geonames.org 现在似乎已经死了
      【解决方案5】:
          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;
      }
      

      这是我用的:)

      【讨论】:

      • 这几乎是完美的,但谷歌返回“英国”而不是“英格兰”或“苏格兰”等。理想情况下,它需要返回“英格兰”等作为应用程序的目的建筑就是在他们两个之间辨认! ://
      • 浏览不同的类型,看看你能不能抓住你想要的。 code.google.com/apis/maps/documentation/geocoding/#Types
      • 这里只是为了超级挑剔,但使用 '===' 而不是 '==' 比较空值更安全。
      • 请注意:“地理编码服务:您必须使用 API 密钥来验证对 Google Maps Platform API 的每个请求。有关更多信息,请参阅g.co/dev/maps-no-account
      【解决方案6】:

      您需要Reverse Geocoder 服务。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2023-03-21
        • 1970-01-01
        • 2011-03-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多