jemz jemz - 28 days ago 4
Javascript Question

How to move marker smoothly without blinking in map

I have problem in my markers every time I get request to our server to get the newly location of my devices and updated the position of my markers on the map,when my vehicle devices move,the marker will jump to the newly location and its flickering.
How can I avoid this not to flickering,or my Marker can move smoothly.

Thank you in advance.

var map;
var marker;
var markerarray =[];

setInterval(function(){

$.ajax({
type: "post",
url: "vehiclecordinates.php",
success: function(data){

coordinates = data.latlng;
vehiclename = data.vehiclename;

for (var i = 0; i < coordinates.length; i++) {

newcoordinate = new google.maps.LatLng(coordinates[i].split(",")[0],coordinates[i].split(",")[1]);
marker = new MarkerWithLabel({
map:map,
labelClass: "mylabels",
labelStyle: {opacity: 1.0},
labelContent: '<div>'+ vehiclename[i]+'</div>',
icon:{
//some options here
},
});

marker.setPosition(newcoordinate);
markerarray.push(marker);
}
}
});

setTimeout(function () {
removeMarkers();
delete marker;
}, 1000);
},5000);

function removeMarkers() {
for(var i = 0; i < markerarray.length; i++) {
markerarray[i].setMap(null);
}
}

Answer

If you don't want them to flicker, don't "remove" them from the map, update their position.

var map;
var marker;
var markerarray =[];

setInterval(function(){
  $.ajax({
    type: "post",
    url: "vehiclecordinates.php",
    success: function(data){
      coordinates = data.latlng;
      vehiclename = data.vehiclename;
      for (var i = 0; i < coordinates.length; i++) {
        newcoordinate = new google.maps.LatLng(coordinates[i].split(",")[0],coordinates[i].split(",")[1]);
        if (markerarray[vehiclename[i]] && markerarray[vehiclename[i]].setPosition){
          markerarray[vehiclename[i]].setPosition(newcoordinate);
        else {
          marker =  new MarkerWithLabel({
            map:map,
            labelClass: "mylabels",
            labelStyle: {opacity: 1.0},
            labelContent: '<div>'+ vehiclename[i]+'</div>',
            icon:{
              //some options here
            }
          });
          marker.setPosition(newcoordinate);
          markerarray[vehiclename[i]] = marker;
        }
      }
    }
  });
},5000);

See example based off the example in this similar question