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
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'));
});
Okay, turns out it just works with event.coordinate
, displaying coordinates in the SRC defined in the layer
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With