mapbox-gl-js icon indicating copy to clipboard operation
mapbox-gl-js copied to clipboard

How to use map.fire to simulate map.on("click")?

Open Roxyi opened this issue 9 years ago • 6 comments

Hi, I tried using fire to simulate click function, but I met a problem.

For example, my click function is:

map.on("click", function(e){
  console.log(e);
});

If you actually click on the map, the results will be: image

Now I need to simulate a user click on the center of the map. My fire function is:

var center =  map.getCenter();
map.fire("click", {lngLat: center});

And the results I got is: image

The problem is that in the results of my fire function, there is no "point". Without the parameter "point", I will not be able to use map.queryRenderedFeatures() to get the layer's features.

I know that I missed the parameter "point" in my fire function, but I cannot find a way to get it.

Any help with this would be greatly appreciated. Thanks!

Roxyi avatar Jul 27 '17 22:07 Roxyi

Hi @Roxyi. You can use Map#project to translate from LngLat to screen coordinates.

jfirebaugh avatar Jul 27 '17 22:07 jfirebaugh

@jfirebaugh Thank you so much. It solved my problem. Also this solved my other question. I was working on getting the features merely based on lat and lng. I think using the projected point, I will be able to do it.

Roxyi avatar Jul 27 '17 22:07 Roxyi

Sorry to dig up this old issue but I'm facing a similar problem:

map.fire("click", {
    lngLat: prevFeature.geometry.coordinates,
    point: map.project(prevFeature.geometry.coordinates)
});

gives me: Uncaught TypeError: Cannot read property 'target' of undefined

Also, since .fire is now deprecated, whats a good alternative to simulate click on map/feature?

Thanks!

3zzy avatar Oct 04 '18 01:10 3zzy

For anyone using this to simulate clicks in test environments like Cypress, I've had success with this:

map.fire('click', { latLng: coords, point: map.project(coords), originalEvent: {} })

justinmanche avatar May 01 '20 04:05 justinmanche

i tried all solution but in my scenario click event is not working can anyone suggest something

jaikumar-Xperate avatar Apr 28 '23 11:04 jaikumar-Xperate

@jaikumar-Xperate it still works, but note that features will be empty. If you're relying on getting information about the clicked features, you need to use queryRenderedFeatures and supply them yourself-

chriszrc avatar Sep 27 '23 15:09 chriszrc