【发布时间】:2019-12-17 05:26:19
【问题描述】:
我正在开发一个分类门户网站,用户可以发布他们的广告,我使用 Google 地理定位功能从浏览器中获取用户的当前位置坐标。
浏览器要求授予权限,但我只想在仅授予权限的情况下显示地图。如果不是,我必须为该位置设置一些默认坐标。
这是我当前的代码:
<div id="map"></div>
<script>
// Note: This example requires that you consent to location sharing when
// prompted by your browser. If you see the error "The Geolocation service
// failed.", it means you probably did not give permission for the browser to
// locate you.
var map, infoWindow;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -34.397, lng: 150.644},
zoom: 13
});
infoWindow = new google.maps.InfoWindow;
document.cookie = "myJavascriptVar=12345";
// Try HTML5 geolocation.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
var my_marker = new google.maps.Marker({
position: pos,
map: map,
"icon": 'map.png',
draggable: true,
});
infoWindow.setPosition(pos);
//infoWindow.setContent('You are here');
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);
}
如何检查浏览器权限是否被授予?
为什么每次我刷新页面都会询问?
【问题讨论】:
-
我只想在获得许可的情况下显示地图。如果不是,我必须为该位置设置一些默认坐标。 - 那是矛盾。你想加载还是不加载?可能您想像这里的许多 Q/A 中解释的那样进行操作。使用默认坐标加载地图,然后更改为用户位置,如果你得到它,即。如果允许的话。