3

I have a button on a leaflet map that when clicked zooms the map to the users current location. This function is working properly.

<button type="button" id="locator" class="btn btn-primary btn-lg">
..
$("#locator").click(function() {
  map.locate({
    setView: true,
    maxZoom: 16
  });

Using the lat and long of the found location I would like to emulate a click event on the intersecting polygon layer. To perform this I use the maps 'locationfound' event to fire a click event at the found location (below). Nothing happens.

map.on('locationfound', function(e) {
  var latlngPoint = new L.LatLng(e.latlng.lng, e.latlng.lat);
  map.fireEvent('click', {
    latlng: latlngPoint
  });
});

The polygon layer has the following click event. The layer click event works fine when clicked manually, but does not execute via passing latlng pair.

var sections = L.geoJson(randall, {
  style: featureStyle,
  onEachFeature: onEachFeature
});

function onEachFeature(feature, featureLayer) {

  featureLayer.bindPopup(feature.properties.ANUM);

  featureLayer.on('click', function(e) {

    console.log('Layer clicked!', e);
  })
};

Heres my jsfiddle.

1 Answer 1

1

This looks like an instance of the XY problem. You don't really want to emulate pointer interactions on Leaflet; what you really want to identify which polygon contains a given point (and the only way of doing that you can think of is to emulate pointer interactions).

If you have a look at the list of Leaflet plugins, you'll see a reference to leaflet-pip and Leaflet.CheapLayerAt. Those should work for your case.

You can of course run your own point-in-polygon geoprocessing via Turf.js or even through WCS.

Also note that the caveats of CheapLayerAt highlight a problem that you would have with your approach of emulating pointer interactions: if the geolocation results are outside of the visible map area, the behaviour would be strange. Vector features in Leaflet are not drawn off-screen, so they don't have event handlers, so they wouldn't react as you would expect.

If you really want to emulate pointer events, do read https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Creating_and_triggering_events and maybe even the source code for https://github.com/Leaflet/prosthetic-hand . I honestly believe that it's more hassle than it's worth for your use case.

Your Answer

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

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