How to bind a click event to a Leaflet canvas GridLayer

canvas, javascript, leaflet

Solution

In Leaflet 1.0, `GridLayer`s do not handle mouse/touch/pointer events (notice their events documentation does not list pointer events, whereas some other layer types do).

Furthermore, the DOM element containing the tiles (a `<div class='leaflet-tile-container>`) has a `pointer-events: none;` CSS rule. This makes the browser ignore pointer events (giving it a tiny bit of better performance).

You'll need to attach the events to the cells themselves (when on your custom `createTile()`) and override the `pointer-events` CSS rule.

Problem

I'm trying to bind a click event to a leaflet plug-in's extension of a canvas GridLayer (using Leaflet 1.0, with Leaflet.MaskCanvas). From the Leaflet Documentation about GridLayer, I would expect that I could bind a click to `coverageLayer` using either ``` // add event listener to determine when layer has been clicked coverageLayer.on('click', function(e) { console.log('clicked the line'); }); // second (alias) method to add event listener coverageLayer.addEventListener('click', function(e) { console.log('clicked the line'); }); ``` but neither of the above seem to be working. Here's a fiddle where I've forked and tweaked the example code from the MaskCanvas plugin. Is there some other way to bind a click to a canvas layer in Leaflet? Edit: `.on()` and `.addEventListener()` are aliases. Previously the question dealt with Leaflet 0.7, and TileLayer. From the old Leaflet Documentation, it appears that TileLayer did not have these events. JSFiddle code has been updated to use Leaflet 1.0.

Original source