是否可以使用地理定位同步用户位置?这样,如果用户正在旅行,他的位置将在页面上更新,有些类似于导航他的位置...
我已经试过了,但是整个 map 一直在刷新,加载需要时间……它工作正常,但是,有没有更好的方法可以让我跟踪用户的位置?
<script src="https://maps.googleapis.com/maps/api/js"></script>
<script src="../dist/geolocationmarker-compiled.js"></script>
<script>
var map, GeoMarker;
setInterval (function initialize() {
var mapOptions = {
zoom: 17,
center: new google.maps.LatLng(-34.397, 150.644),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map_canvas'),
mapOptions);
GeoMarker = new GeolocationMarker();
GeoMarker.setCircleOptions({fillColor: '#808080'});
google.maps.event.addListenerOnce(GeoMarker, 'position_changed', function() {
map.setCenter(this.getPosition());
map.fitBounds(this.getBounds());
});
google.maps.event.addListener(GeoMarker, 'geolocation_error', function(e) {
alert('There was an error obtaining your position. Message: ' + e.message);
});
console.log('updating');
GeoMarker.setMap(map);
},10000);
google.maps.event.addDomListener(window, 'load', initialize);
if(!navigator.geolocation) {
alert('Your browser does not support geolocation');
}
</script>
<body>
<div id="map_canvas"></div>
</body>
最佳答案
位置改变时不要重新创建 map ,只更新标记在 map 上的位置。
var map, GeoMarker;
function initialize() {
var mapOptions = {
zoom: 17,
center: new google.maps.LatLng(-34.397, 150.644),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map_canvas'),
mapOptions);
}
setInterval (function() {
if (!GeoMarker) {
GeoMarker = new GeolocationMarker();
}
GeoMarker.setCircleOptions({fillColor: '#808080'});
google.maps.event.addListenerOnce(GeoMarker, 'position_changed', function() {
map.setCenter(this.getPosition());
map.fitBounds(this.getBounds());
});
google.maps.event.addListener(GeoMarker, 'geolocation_error', function(e) {
alert('There was an error obtaining your position. Message: ' + e.message);
});
console.log('updating');
GeoMarker.setMap(map);
},10000);
google.maps.event.addDomListener(window,'load',initialize);
if(!navigator.geolocation) {
alert('Your browser does not support geolocation');
}
关于javascript - 在javascript中将用户位置与谷歌地图同步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31206678/