0

My leaflet project has a few user drawn shapes on it. When clicking on the shape, another element such as a sidebar will print out the stats. If I click on the map layer, the element is supposed to reset.

I tried using the map.on('click') event, but it listens to all user drawn layers as well as the map layer. I only want the event to listen to the map layer.


map.on('click', onBackgroundClick);

function onBackgroundClick(e)
{
    let type = e.layerType;

    if (type !== 'polygon' && type !== 'polyline' && type !== 'marker' && type != 'rectangle')
    {
          //reset sidebar state
    }
}

What changes do I make to the event such that it only listens to the map layer. Is there a better approach to this problem?

disguisedtoast
  • 149
  • 1
  • 4
  • 15

4 Answers4

1

Or you can call stopPropagation in children components, thus click events on children won't be propagated through DOM tree, but just on map they will.

hovnozrout
  • 121
  • 2
0

To add click on creation of a layer:

L.featureGroup(arr).on('click', function(){/* Your Code*/ });

You can always use on method to add event listener .

nAviD
  • 2,784
  • 1
  • 33
  • 54
0

The issue in your attempt has a similar root cause as in your other question, i.e. event.layerType is set only by Leaflet.draw plugin, only when a new feature has been created by a user.

Here a solution could consist in testing if the clicked layer is not part of your features, if the latter are all part of a Layer Group, which is probably the case if you use Leaflet.draw:

const clickedLayer = e.target;
if (!myLayerGroup.hasLayer(clickedLayer))

Another possible solution could be on the contrary to test if the clicked layer is the Tile Layer:

const clickedLayer = e.target;
if (clickedLayer === myTileLayer)

// or
if (clickedLayer instanceof L.TileLayer)
ghybs
  • 47,565
  • 6
  • 74
  • 99
0

Here is the solution I went with.

I'm not super happy with it, but it works for my case.

It basically just checks if the element clicked is of type path and if so, stop executing the map click handler body

map.on('click', function(e) {
    if (e.originalEvent.target.nodeName == 'path')
        return;
    
    // map-only click logic below
    sidebar.classList.remove('active');
LukasKroess
  • 125
  • 2
  • 13