我正在开发一个分类门户,他们的用户可以发布他们的广告,并且我使用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);
}
我如何检查是否授予浏览器权限?
为什么每次我刷新页面时都会询问?
Geolocation.watchPosition()
检查错误代码并相应地设置条件
https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/watchPosition