【问题标题】:Geolocation result display NaN地理位置结果显示 NaN
【发布时间】:2019-05-22 10:11:57
【问题描述】:

我想获取访问我网站的用户的地理位置。我喜欢这个简单的 'https://www.w3schools.com/html/html5_geolocation.asp' 代码,当我自己使用 try it 时,它显示了纬度和经度。我在我的网站上试过了,没问题。但另一个尝试给了我 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>

【问题讨论】:

    标签: javascript html


    【解决方案1】:

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

    您可以在这里阅读更多信息:Geolocation Without SSL connection

    【讨论】:

    • 非常感谢您的回复。我真的明白这一点,我的网站是 HTTPS。这甚至发生在我在“w3schools.com/html/html5_geolocation.asp”使用“自己尝试”时。任何进一步的帮助
    • 我建议您仔细查看浏览器的开发人员工具控制台,因为通常会在此处记录有关错误的更详细信息。我只能这么说,因为我无法复制您的问题。
    • 非常感谢。我发现这仅与桌面浏览器有关。而且由于我只需要在移动应用程序上使用它并且它在移动浏览器上运行良好,我只是忽略了它。再次感谢
    猜你喜欢
    • 2013-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-05
    相关资源
    最近更新 更多