地理定位在 Chrome/Safari 中失败,而不是 Firefox/Opera

Geolocation fails in Chrome/Safari, not Firefox/Opera

我正在尝试 运行 navigator.geolocation.getCurrentPosition 通过 rails 应用 @ localhost:3000。相关代码取自 Google's Geolocation Demo 和 运行 到 rails.

目前,地理定位 偶尔 通过 Chrome 成功(约 10% 的时间),总是 几乎有效在 Opera 中立即运行,约 80% 的时间在 Firefox 中运行,在 Safari 中总是立即失败。

在失败的浏览器中,只有 Safari returns 控制台出现错误。具体来说,

Access to geolocation was blocked over insecure connection to http://localhost:3000

这对 Safari 来说是有意义的,但是据我了解 localhost 在其他浏览器(包括 Chrome)中被列入白名单并且应该可以正常工作。更不用说,它工作 一些 次 - 并且总是在 Opera 中。

在失败的实例中,console/inspector 不会返回任何内容,并且 getCurrentPosition 方法永远不会 returns 任何内容,除非我设置了 timeout 参数(在这种情况下它 returns 超时错误)。

有什么想法会导致地理定位在某些浏览器上始终在本地工作,而在其他浏览器上不一致,而在其他浏览器上根本不工作?我完全被这个难住了——任何想法都值得赞赏。下面的代码

geolocation.js:

var map, infoWindow;
function initMap() {
    map = new google.maps.Map(document.getElementById('map'), {
        center: {lat: -34.397, lng: 150.644},
        zoom: 6
    });
    infoWindow = new google.maps.InfoWindow;

    // Try HTML5 geolocation.
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function(position) {
            var pos = {
                lat: position.coords.latitude,
                lng: position.coords.longitude
            };

            infoWindow.setPosition(pos);
            infoWindow.setContent('Location found.');
            infoWindow.open(map);
            map.setCenter(pos);
        }, function() {
            handleLocationError(true, infoWindow, map.getCenter());
        });
    } else {
        // Browser doesn't support Geolocation
        handleLocationError(false, infoWindow, map.getCenter());
    }
}

function handleLocationError(browserHasGeolocation, infoWindow, pos) {
    infoWindow.setPosition(pos);
    infoWindow.setContent(browserHasGeolocation ?
        'Error: The Geolocation service failed.' :
        'Error: Your browser doesn\'t support geolocation.');
    infoWindow.open(map);
}

views/contact_details/new.html.slim

#map
script(src="/geolocation.js")
<script async defer src="//maps.googleapis.com/maps/api/js?key=AIzaSyBSSvl9zJIZIXXgp7LMYKNU7-l9cwJSAiw&callback=initMap"></script>

我也遇到过这种情况。最新的 Chrome 65 版本(2018 年 3 月)中似乎存在一个错误,该错误导致 getCurrentPosition() 和 watchPosition() 超时不一致,而不是 return 结果。到目前为止,我一直无法找到解决此问题的方法,因此目前正在等待 Google.

的修复

作为一项临时措施,我建议将 'timeout' 值作为第三个参数传递给 getCurrentPosition() 调用,以便至少让函数在一段时间后恢复正常处理。然后,您可以通过错误处理函数将信息传递给用户。

navigator.geolocation.getCurrentPosition(
    function (position) {
        // on success this will be called.
    }, 
    function (err) {
        // on error this will be called (including timeout).
    },
    {
        timeout: 5000
    }
);

我在此处的示例中使用了类似的方法:Chrome Geolocate Bug

这里有一个看起来相关的错误报告:Chromium Issue 820945