Search code examples
javascriptopenlayers

get coordinates event map openlayers 4.6.5 ~ 5


I try to get the coordinates of a click on a openlayers map. My code is as follows:

const localmap = new ol.Map({
    layers: [
      new ol.layer.Tile({
        source: new ol.source.OSM()
      })
    ],
    target: 'map',
    view: new ol.View({
      center: [0, 0],
      zoom: 2
    })
  });

  function getPosition(event){
    console.log(localmap.getEventCoordinate(event));
}

  localmap.on('click', getPosition(event));

But the only thing I get this way is an error:

Uncaught TypeError: Cannot read property 'changedTouches' of undefined

I tried with adding the listener as

localmap.on('click', getPosition);

It displays an array on each click but it's filles with Nan values.

I tried seraching doc and all but it's either too old or writing the function directly in the listener, which I don't want cause I want to be able to remove it

Anybody has a clue to get those coordinates in ol 4.6.5 ~ 5?

Thanks


Solution

  • Okay, turns out it just works with event.coordinate, displaying coordinates in the SRC defined in the layer