4

I need to emulate a user click on my MapBox GL JS map.

I doesn't matter where in my map: could be useful to do in the point at the center of my maps if this could be easier.

UPDATE

I've found here https://stackoverflow.com/questions/18323105/programmatically-opening-a-popup-in-a-mapbox-map something that could be useful ...

map.fireEvent('click', {latlng: L.latLng(28.04419, -81.947864)});

... but seems to be something about Leaflet

I'd like my code coud be something like this ("broken code" ... )

    bounds = map.getBounds();
    x = bounds._ne.lng;
    y = bounds._ne.lat;

    map.fireEvent('click', {latlng: L.latLng(x, y)});

Does fireEvent exist in MapBox GL JS or are there alternatives?

4
  • What is the question? What have you tried?
    – BradHards
    Sep 3, 2016 at 1:25
  • You're right .. I've tried to add some more details and a "pseudo" code example ...
    – Cesare
    Sep 3, 2016 at 14:18
  • 1
    So you want to fire it using some other bit of client side code, rather than from some server-side action? mapbox.com/mapbox-gl-js/api/#MapMouseEvent ?
    – BradHards
    Sep 3, 2016 at 23:12
  • Yes! Please, could your give me an example? Thanks in Advance!!!
    – Cesare
    Sep 4, 2016 at 6:55

3 Answers 3

3

In the doc for Map:

The Map class mixes in Evented methods.

Doc for Evented has info on fire so you can use something like map.fire('click', { lngLat: ll, point: pt }).

1
3

Any answer that depends on map.fire is deprecated.

To simulate a click in MapboxGL, the easiest method involves using the .click() method in any element.

document.querySelector('canvas').click()

This may not be what you're looking for; you might wish to click at a certain location. This is where MouseEvent is your friend:

const map = document.querySelector('canvas')

const event = new MouseEvent({
  clientX: 200,
  clientY: 200,
  bubbles: true
}

map.dispatchEvent(event)

This may not work if you have more than one map or html canvas on the screen. If you find yourself selecting the wrong element with the query selector, add id="map" to your map html element, and use document.querySelector('#map') instead.

1
  • I needed new MouseEvent('click', {...
    – kmanzana
    May 12, 2022 at 23:23
0

Try this:

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

From: https://github.com/mapbox/mapbox-gl-js/issues/5060

Your Answer

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

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