[GIS] Add / remove an ImageOverlay from Leaflet map

javascriptleaflet

My goal is to add / hide an L.ImageOverlay image from my leaflet map on click. This code should work, but it only adds image and does not hide it on a following click.

var map = L.map('mainMap').setView([56.06, 92.500], 10);

function loadImage(e) {

    var imageUrl = 'data/kr1_cut.png',
        imageBounds = [[55.819224, 92.170872], [56.324808, 92.480904]],
        image = L.imageOverlay(imageUrl, imageBounds);
    // remove image layer if it already exists
    if (map.hasLayer(image)) {
        map.removLayer(image);
    }
    else {
        image.addTo(map);
    }
}

map.on('click', loadImage);

So what am I doing wrong?

Best Answer

First there is typo in the method call: it should be map.removeLayer(image);.

Second thing is that layer should be defined outside of the function, otherwise a new layer is created at each function call:

var map = L.map('mainMap').setView([56.06, 92.500], 10);

var imageUrl = 'data/kr1_cut.png',
    imageBounds = [[55.819224, 92.170872], [56.324808, 92.480904]],
    image = L.imageOverlay(imageUrl, imageBounds);

function loadImage(e) {
  // remove image layer if it already exists
  if (map.hasLayer(image)) {
    map.removLayer(image);
  }
  else {
    image.addTo(map);
  }
}

map.on('click', loadImage);