I have a leaflet app with some geojson line features on it. The weight of the lines are 1px and I have a popup bound to them on a click event.
The problem is, in order to click the line, your cursor has to be over the exact pixel and it is very frustrating.
Is there a way to make the click event buffer around the line by 2 or 3 pixels? I do not want to make the line thicker, as there are too many features and it will look very crowded.
Thanks in advance!
You would very probably be interested in the Leaflet.AlmostOver plugin:
This plugin allows to detect mouse click and overing events on lines, with a tolerance distance.
It is useful if paths are drawn with a very small weight, or for clicks detection on mobile devices, for which finger precision can be a problem.
Play with online demo.
It requires Leaflet.GeometryUtil.
Live example:
var map = L.map('map').setView([48.86, 2.35], 11);
var line = L.polyline([
[48.87, 2.3],
[48.87, 2.4]
], {
weight: 1
}).bindPopup('line of width 1 px with almostOver').addTo(map);
map.almostOver.addLayer(line);
map.on('almost:click', function(e) {
var layer = e.layer;
if (layer.openPopup) {
layer.fire('click', e);
}
});
var line2 = L.polyline([
[48.85, 2.3],
[48.85, 2.4]
], {
weight: 1,
color: 'red'
}).bindPopup('line of width 1 px without almostOver').addTo(map);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);
<link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css" integrity="sha512-Rksm5RenBEKSKFjgI3a41vrjkw4EVPlJ3+OiI65vTjIdo9brlAacEuKOiQ5OFh7cOI1bkDwLqdLw3Zg0cRJAAQ==" crossorigin="" />
<script src="https://unpkg.com/[email protected]/dist/leaflet-src.js" integrity="sha512-IkGU/uDhB9u9F8k+2OsA6XXoowIhOuQL1NTgNZHY1nkURnqEGlDZq3GsfmdJdKFe1k1zOc6YU2K7qY+hF9AodA==" crossorigin=""></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/src/leaflet.geometryutil.js"></script>
<script src="https://rawgit.com/makinacorpus/Leaflet.AlmostOver/b1629f00c9708d4843829f2aef9e5791d0ad4a53/src/leaflet.almostover.js"></script>
<div id="map" style="height: 200px"></div>