Skip to content Skip to sidebar Skip to footer

Remove The Previous Marker And Add Marker In The Updated Lat Lng

I have a gps device which sends data every 10 seconds. I am saving the data (lat, lng) in the MySql database., I am retrieving the data from the DB and putting the markers on those

Solution 1:

You have two options, both involve keeping a reference to the marker outside of the displayLocation function:

  1. use the reference to move the existing marker
var marker;
functiondisplayLocation(location) {
  console.log(location.lat)
    var position = new google.maps.LatLng(parseFloat(location.lat), parseFloat(location.lng));
    if (marker && marker.setPosition) {
      // if the marker already exists, move it (set its position)
      marker.setPosition(location);
    } else {
      // create a new marker, keeping a reference
      marker = new google.maps.Marker({
        map: map, 
        position: position,
        title: 'test!'
      });
    }
}
  1. remove the existing marker from the map and create a new one
var marker;
functiondisplayLocation(location) {
  console.log(location.lat)
    var position = new google.maps.LatLng(parseFloat(location.lat), parseFloat(location.lng));
    if (marker && marker.setMap) {
      // if the marker already exists, remove it from the map
      marker.setMap(null);
    }
    // create a new marker, keeping a reference
    marker = new google.maps.Marker({
      map: map, 
      position: position,
      title: 'test!'
    });
}

Solution 2:

You should do

map.addMarker(newMarkerOptions()
        .position(newLatLng(parseFloat(location.lat), parseFloat(location.lng)))
        .title("test!"));

in displayLocation function

Post a Comment for "Remove The Previous Marker And Add Marker In The Updated Lat Lng"