[GIS] Simulate click to map on specific coordinates and layer in OpenLayers

javascriptopenlayers

When a user click on a specific feature, I display a simple overlay (popup). But I need to display this popup on a closest features when a user search a random location.

So, I search to simulate the 'click' event on a specific coordinates to simulate map click event and display my popup.

I could use dispatchEvent('click'), but this method only trigger the map click event without coordinates.

And without coordinates, it's impossible to set overlay position…

Edit :

In my environement, i have an unlimited maps in the DOM page (WordPress widget / PHP + JS). Sometimes, the WordPress system call the popup of an other map. To create a simple code, my idea was to directly call the click event of the targeted map.

Others solutions exists but i need to now how to fire click event with specific coordinates ? Just out of curiosity.

dispatchEvent doc.

Best Answer

If you look at the documentation for dispatchEvent(event) method, description of event parameter says: The event parameter can either be a string or an Object with a type property. This means you can construct your own event where type propoperty will have value 'click' and coordinate property will hold desired click coordinates.

Click event simulation for layer myLayer could then look something like this:

var evt = {};
evt.type = 'click';
evt.coordinate = [];
evt.coordinate[0] = 6633511;
evt.coordinate[1] = 4079902;
myLayer.dispatchEvent(evt);

You would then catch the click event on layer with:

myLayer.on('click', function(evt) {
  console.log('layer click: ' + evt.coordinate);
});
Related Question