2

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?

4

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);
| improve this answer | |
  • Leaflet's Guru :) – Taras Oct 23 '19 at 16:07
  • I'm answering questions from very selfish reasons: to learn about Leaflet and GIS. Rarely I know answer immediately, I have to learn how to solve it. I'm total GIS amateur, just mountain biker who hates to get lost and so I'm making my own maps :-). But it's true that I have 45+ years of programming experience. – TomazicM Oct 23 '19 at 16:31
0

You have typo here..

map.removLayer(image);

must be

map.removeLayer(image);

| improve this answer | |

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.