html5 地理定位不适用于 Safari 浏览器

html5 geolocation not working on safari browser

致力于html5地理定位。

在 mozilla、chrome、IE 上试过。在它们上工作正常但不适用于 safari。在 mac 上的 safari(8.0.5)、windows

上的 safari(5.1) 上测试

只需点击 url

http://www.w3schools.com/html/html5_geolocation.asp

http://www.w3schools.com/html/tryit.asp?filename=tryhtml5_geolocation

  <!DOCTYPE html>
<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>

它给出了弹出窗口 Allow/Disallow 但在允许它之后什么也不做。 我已经在 Mac 上通过 wi-fi 测试了 safari 但也没有在 wi-fi 和 LAN 上测试笔记本电脑。

您连接的是 Wi-Fi 还是有线网络?

当您未连接 Wi-Fi 时,safari 似乎有问题。

来源

Geolocation not workin on Safari 5.x on Windows 7/XP

Geolocation in Safari 5

基于问题中的示例,以下是完整的工作片段:

<p id=demo>
<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;
}
getLocation()
</script>

问题中的实际示例是不完整的,因此它本身永远不会按原样做任何事情。因此,在没有看到完整代码的情况下,很难知道 Mozilla、Chrome 和 IE 中可能工作的内容。

如果以上代码片段在您的 Safari 中仍不适合您,请打开 Safari 的 Web 检查器(例如,从 开发 菜单或右键单击页面并选择 Inspect Element),然后转到那里的 Console 选项卡,查看记录了哪些错误。

目前,就代码片段而言,需要注意一些基本要点:

  • 脚本必须实际调用 getLocation() 函数(而不只是定义它)
  • 文档实际上必须有一个 id=demo 元素
  • 脚本应放在 id=demo 元素之后(如果将对 getLocation() 的调用放在例如文档的 head 中,它将不起作用, 因为它将 运行 在 id=demo 元素存在于 DOM)
  • 之前

永远不要使用 w3schools.com 做任何事。它很草率,非常不可靠,维护也很差。而是使用 MDN. For example, MDN has a very good Using geolocation page, with complete code for a good live example.

很遗憾,Apple 不通过 HTTP 连接提供地理定位数据。您需要 HTTPS 才能访问 Safari 上的客户端地理位置。

JavaScript 地理定位并未要求用户在 iOS 和 Desktop Safari 上共享位置。 Turner 指出,站点需要 HTTPS 和错误处理才能让 Safari 共享位置。一旦我添加了 SSL 证书,它就成功了!