地理位置结果显示NaN

时间:2019-05-22 10:11:58

标签: javascript html

我想获取访问我网站的用户的地理位置。当我自己尝试使用时,我喜欢这个简单的“ 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>

1 个答案:

答案 0 :(得分:0)

该代码是正确的,因此我仅猜测可能是您在没有https的服务器/域上尝试使用您的代码。现在,在一些主流浏览器中,这是强制性的,因此,如果您位于https下,则只能使用geolocation api。

您可以在此处了解更多信息:Geolocation Without SSL connection