javascript - 地理位置结果显示 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>
解决方案
代码是正确的,所以我只是猜测您可能正在没有 https 的服务器/域上尝试您的代码。这现在在几个主流浏览器中都是强制的,所以你只能在 https 下使用 geolocation api。
您可以在此处阅读更多相关信息:没有 SSL 连接的地理位置
推荐阅读
- dart - VS Code-'dart' 不是内部或外部命令、可运行程序或批处理文件
- pentaho - 如何保持消息的顺序,从 jms 消费者转换为 pentaho 中的文件
- php - 使用 Laravel 中的中间件使用单表用户进行多身份验证登录
- python - 提高计算与熊猫中特定条件匹配的随机样本的性能
- reactjs - React - URL 正在改变,但视图没有改变
- php - 我需要在目录中的所有文件中自动替换我的代码的某些部分
- css - 使用css在li之间添加连接线
- javascript - 视图中的 Chart.js 未定义变量
- javascript - mat-menu 冷冻(有棱角的材料)
- pip - pip 抱怨包裹