首页 > 解决方案 > 地理位置结果显示 NaN

问题描述

我想获取访问我网站的用户的地理位置。我喜欢这个简单的“ https://www.w3schools.com/html/html5_geolocation.asp ”代码,当我自己使用它时,它会显示经纬度。我在我的网站上试过了,没问题。但另一个尝试给了我 NaN。来自 w3school 网站和我的网站。请问,我该如何解决这个问题?

<html>
<body>

<p>Click the button to get your coordinates.</p>

<button onclick="getLocation()">Try It</button>

<p id="demo"></p>

<script>
var x = document.getElementById("demo");

function getLocation() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(showPosition);
  } else { 
    x.innerHTML = "Geolocation is not supported by this browser.";
  }
}

function showPosition(position) {
  x.innerHTML = "Latitude: " + position.coords.latitude + 
  "<br>Longitude: " + position.coords.longitude;
}
</script>

</body>
</html>

<script>
var x = document.getElementById("demo");

function getLocation() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(showPosition);
  } else { 
    x.innerHTML = "Geolocation is not supported by this browser.";
  }
}

function showPosition(position) {
  x.innerHTML = "Latitude: " + position.coords.latitude + 
  "<br>Longitude: " + position.coords.longitude;
}
</script>

标签: javascripthtml

解决方案


代码是正确的,所以我只是猜测您可能正在没有 https 的服务器/域上尝试您的代码。这现在在几个主流浏览器中都是强制的,所以你只能在 https 下使用 geolocation api。

您可以在此处阅读更多相关信息:没有 SSL 连接的地理位置


推荐阅读