C graphics C graphics - 2 months ago 25
Javascript Question

How to update a marker's location on google map without having to refresh entire map?

I am trying to display the current location on google map every 3 sec.It technically works, however the entire map refreshes every 3 seconds too. How can I display the current location smoothly on the map without having to refresh the entire map ( unless necessary such as when the agent goes off the map and current location no longer exist on the map)?

Here is my code:

<!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>

Answer

Your best bet is to use navigator.geolocation.watchPosition which calls a function only if the postion of the agent changes. So

1) you do not need to set a timer function to constantly refresh

2) the panning is handled by map.panTo() in this sample so that issue is addressed too.

3) the code below also uses the navigator.geolocation

<script>
var x = document.getElementById("demo");
function getLocation() {
    if (navigator.geolocation) {
        navigator.geolocation.watchPosition(showPosition);
    } else {
        x.innerHTML = "Geolocation is not supported by this browser.";
    }
}
function showPosition(position) {
    x.innerHTML = "Latitude: " + position.coords.latitude +
    "<br>Longitude: " + position.coords.longitude;
}
</script>

Hope it all heped