Search code examples
esriarcgis-js-api

How can i remove a graphic by id in the graphic layer


How can i remove a graphic by id in the graphic layer.I am using esri-javascript-api.Hope any answer.


Solution

  • Let say the graphicLayer is the map graphic's layer, the id attribute is named "id" and you want to remove the graphic with the id 0;

    var graphicLayer = map.graphics;
    var idAttribute = "id";
    var idValue = 0;
    
    var toBeRemoved = graphicLayer.graphics.filter(function(graphic) {
      return graphic.attributes[idAttribute] == idValue;
    })[0];
    
    graphicLayer.remove(toBeRemoved);
    

    You could create a function for doing this in batch

    function removeGraphicById(graphicLayer, idAttribute, idValue) {
        var toBeRemoved = graphicLayer.graphics.filter(function(graphic) {
          return graphic.attributes[idAttribute] == idValue;
        })[0];
    
        graphicLayer.remove(toBeRemoved);
    };
    
    var idsToDelete = [0, 1, 2, 3, 4];
    
    idsToDelete.forEach(function(id) {
      //using map.graphics layer for instance
      removeGraphicById(map.graphics, "id", id);
    });