4

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?

2 Answers 2

6

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

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.removeLayer(image);
  } else {
    image.addTo(map);
  }
}

map.on('click', loadImage);
1
  • Leaflet's Guru :)
    – Taras
    Oct 23, 2019 at 16:07
1

You have typo here..

map.removLayer(image);

must be

map.removeLayer(image);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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