Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 520
Clement Avatar asked Jul 02 '18 11:07

Clement


2 Answers

This code will work. Note that coordinates you will get are in EPSG:3857 projection use ol.proj.transform() to convert them in to EPSG:4326 projection. To know more about projections visit https://lyzidiamond.com/posts/4326-vs-3857. You must read this if you are going to work on openlayers frequently.

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
        })
});

localmap.on('singleclick', function (evt) {
    console.log(evt.coordinate);

    // convert coordinate to EPSG-4326
    console.log(ol.proj.transform(evt.coordinate, 'EPSG:3857', 'EPSG:4326'));
});
like image 96
capnam Avatar answered Sep 20 '22 15:09

capnam


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

like image 37
Clement Avatar answered Sep 17 '22 15:09

Clement