I would like to know how I can check if I have an existing Map Layer before I call map.removeLayer(layer). I am having an issue because I am calling that even if there isn't one to remove.

if (document.getElementById('layer').checked) {
      layer = new esri.layers.ArcGISDynamicMapServiceLayer("---url here---", { "opacity": 1 });
  else {

If the box is unchecked, it will try to remove a non-existing layer. How do I get around this?

1 Answer 1


You could loop through map.layerIds to obtain the id of each layer already in the map and compare the id values directly.

Or compare a distinctive property (like the url) to the layer you intend to add. To get that property, you would first call the method map.getLayer() to get the layer, then you can access the the url property.

var existingLayer = map.getLayer(layer_id);
if (existingLayer.url == addLayer.url) {
  //add layer

(If you didn't provide an id during initial creation, the API will assign one automatically like mymap_layer0 or similar depending on the name of the tag that holds the map object).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.