简体   繁体   中英

Remove specific markers from a map?

I have a Google Map with a bunch of markers.

I add markers to the map one-by-one and need to remove individual markers one-by-one too when required, using individual IDs.

Currently I have some horrible, verbose code, involving a global array of markers, an ID added as metadata to each marker, and a clunky method for looking up a marker's position within the array, as follows:

  var markersArray = [];
  function getPositionById(markerId, arr) { 
      for (var i = 0; i < arr.length; i++) { 
          if (arr[i].metadata.id === markerId) { 
                  return i;
          }
      }
      return null;
  }
  function removeMarker(markerId) { 
      var marker_position = getPositionById(markerId, markersArray);
      if (marker_position !== null) {
          markersArray[marker_position].setMap(null);
          markersArray.splice(marker_position,1);
      }
  }
  function setMarker(position, markerId) {
      removeMarker(markerId);
      var temp_marker = new google.maps.Marker({
          position: position
      });
      temp_marker.setMap(map);
      temp_marker.metadata = { id: markerId };
      markersArray.push(temp_marker);
  }

Could anyone suggest an even slightly more elegant way to do it?

Given that to remove a marker from the Map you need to use setMap(null), means that you need to have a reference to that marker.

The way you presented in your question doesn't look as horrible as you think, but another way to do it is to use a map instead of an array (not sure if map is the best term to use here since we are already working with the Google maps Map), nonetheless, using a map would rid you from the getPositionById() function, off course this assumes that all your markerIds are unique.

Your code would look something like this.

var markers = {};

function removeMarker(markerId) { 
    if(markers[markerId]){
        markers[markerId].setMap(null);
        delete markers[markerId];
    }
}
function setMarker(position, markerId) {
    removeMarker(markerId);
    var temp_marker = new google.maps.Marker({
        position: position
    });
    temp_marker.setMap(map);
    temp_marker.metadata = { id: markerId };
    markers[markerId] = temp_marker;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM