【发布时间】:2018-03-20 08:20:36
【问题描述】:
我正在尝试通过 Rails 应用程序 @localhost:3000 运行 navigator.geolocation.getCurrentPosition。相关代码取自Google's Geolocation Demo,通过rails运行。
目前,地理定位偶尔通过 Chrome 成功(大约 10% 的时间),总是在 Opera 中几乎立即起作用,大约 80% 的时间在Firefox 并且在 Safari 中总是立即失败。
在失败的浏览器中,只有 Safari 在控制台中返回错误。具体来说,
Access to geolocation was blocked over insecure connection to http://localhost:3000
这对 Safari 来说是有意义的,但据我了解,localhost 在其他浏览器(包括 Chrome)中被列入白名单并且应该可以正常工作。更不用说,它在一些次中工作 - 并且总是在 Opera 中。
在失败的实例中,不会向控制台/检查器返回任何内容,并且 getCurrentPosition 方法永远不会返回任何内容,除非我设置了 timeout 参数(在这种情况下,它会返回超时错误)。
有什么想法会导致地理定位在某些浏览器上始终如一地在本地工作,在其他浏览器上不一致,而在其他浏览器上则根本不工作?我完全被这个难住了——任何想法都值得赞赏。代码如下
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>
【问题讨论】:
标签: google-maps google-chrome geolocation maps