Mapbox-gl-js: How to use map.fire to simulate map.on("click")?

Created on 28 Jul 2017  路  4Comments  路  Source: mapbox/mapbox-gl-js

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!

Most helpful comment

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: {} })

All 4 comments

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

@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.

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!

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: {} })
Was this page helpful?
0 / 5 - 0 ratings

Related issues

PBrockmann picture PBrockmann  路  3Comments

stevage picture stevage  路  3Comments

jfirebaugh picture jfirebaugh  路  3Comments

samanpwbb picture samanpwbb  路  3Comments

aderaaij picture aderaaij  路  3Comments