Remove the previous marker and add marker in the updated lat lng

后端 未结 2 453
你的背包
你的背包 2020-12-22 14:44

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 o

相关标签:
2条回答
  • 2020-12-22 15:19

    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;
    function displayLocation(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;
    function displayLocation(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!'
        });
    }
    
    0 讨论(0)
  • 2020-12-22 15:19

    You should do

    map.addMarker(new MarkerOptions()
            .position(new LatLng(parseFloat(location.lat), parseFloat(location.lng)))
            .title("test!"));
    

    in displayLocation function

    0 讨论(0)
提交回复
热议问题