我有一个代码,但问题是watchposition()正在重新编码完整的地图。我想要的是一个只刷新标记位置的代码。这就是我所做的:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Geo Location</title>
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map-canvas{ height: 100% }
</style>
<script type="text/javascript">
function onSuccess(position) {
var lat=position.coords.latitude;
var lang=position.coords.longitude;
var myLatlng = new google.maps.LatLng(lat,lang);
var mapOptions = {zoom: 4,center: myLatlng};
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var marker = new google.maps.Marker({position: myLatlng,map: map});
}
function onError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
var watchID=navigator.geolocation.watchPosition(onSuccess,onError{timeout:30000 });
</script>
</head>
<body>
<div id="map-canvas"></div>
</body>
</html>
答案 0 :(得分:0)
使用setPosition()
......这样吗?
https://plnkr.co/edit/UgCEnQ?p=preview
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
</head>
<body>
<style>
#map {
width: 100%;
height: 300px;
}
</style>
<div id="map"></div>
<script>
var marker, map;
function initMap() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
var myLatLng = new google.maps.LatLng(lat, lng);
map = new google.maps.Map(document.getElementById('map'), {
center: myLatLng,
zoom: 18
});
if (marker != undefined) {
marker.setPosition(myLatLng);
} else {
marker = new google.maps.Marker({
position: myLatLng,
map: map
});
}
});
}
}
</script>
<script src="https://maps.google.com/maps/api/js?callback=initMap" async defer></script>
</body>
</html>