我想每3秒显示一次谷歌地图上的当前位置。它在技术上可行,但整个地图每3秒刷新一次。我怎样才能在地图上平滑地显示当前位置,而无需刷新整个地图(除非必要,例如当代理人离开地图并且当前位置不再存在于地图上时)?如何更新谷歌地图上的标记位置,而无需刷新整个地图?
这里是我的代码:
<!DOCTYPE html>
<html>
<body>
<p id="demo">It displays your current location:</p>
<div id="mapholder"></div>
<div id="time"></div>
<script>
window.onload = getLocation();
var x = document.getElementById("demo");
var displayTime = document.getElementById("time");
function getLocation() {
if (navigator.geolocation) {
// navigator.geolocation.getCurrentPosition(showPosition,showError);
setInterval(function() {
navigator.geolocation.getCurrentPosition(showPosition,showError);
var time = new Date();
displayTime.innerHTML = time.getHours() + ":" + time.getMinutes() + ":" + time.getSeconds();
}, 3000);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
var latlon = position.coords.latitude+","+position.coords.longitude;
var img_url = "http://maps.googleapis.com/maps/api/staticmap?center="
+latlon+"&markers=size:mid%7Ccolor:red%7C"+latlon+"&zoom=14&size=400x300&sensor=false";
document.getElementById("mapholder").innerHTML = "<img src='"+img_url+"'>";
}
function showError(error) {
switch(error.code) {
case error.PERMISSION_DENIED:
x.innerHTML = "User denied the request for Geolocation."
break;
case error.POSITION_UNAVAILABLE:
x.innerHTML = "Location information is unavailable."
break;
case error.TIMEOUT:
x.innerHTML = "The request to get user location timed out."
break;
case error.UNKNOWN_ERROR:
x.innerHTML = "An unknown error occurred."
break;
}
}
</script>
</body>
</html>
您正在使用静态地图。要改变它,你必须重新加载它。如果您想动态更新Google地图上的标记,请使用Google Maps JavaScript API v3。 – geocodezip 2014-10-10 22:42:17
正如@geocodezip所说,Google的JavaScript API提供的地图对于此任务会更好。你有使用静态地图的具体原因吗? – 2014-10-13 02:42:01