How to get the mouse coordinates stored in a variable in open layers?


How to get the mouse coordinates stored in a variable in open layers?



I have a code that displays the mouse position outside of the map in openlayers !
what if I want to save those coordinates when I call the js mouse events onmousedown and onmouseup ?



I have the following code :


const mousePositionControl = new MousePosition({
coordinateFormat: createStringXY(4),
projection: 'EPSG:4326',
className: 'custom-mouse-position',
target: document.getElementById('mouse-position'),
undefinedHTML: ' '
});

const map = new Map({
controls: defaultControls({
attributionOptions: {
collapsible: false
}
}).extend([mousePositionControl]),
layers: [
new TileLayer({
source: new OSM()
})
],
target: 'map',
view: new View({
center: [0, 0],
zoom: 2
})
});




1 Answer
1



I see two easy ways of doing this.



First one, simply listen for your OpenLayers Map 'click' (or singleclick) event.
You can then get the cursor coordinates as follow:


myMap.on('click', function(evt){
// Get the pointer coordinate
let coordinate = ol.proj.transform(evt.coordinate);
}



Second one is, keep track of the pointer coordinate each time it is moved on the map, using the 'pointermove' event, then just read them when you want:


let coord = ;

// We track coordinate change each time the mouse is moved
myMap.on('pointermove', function(evt){
coord = evt.coordinate;
}

// Anytime you want, simply read the tracked coordinate
document.addEventListener('mousedown', function(){
console.log(coord);
});





Thanks ! pointermove works !
– Jaahnvi Mohan
Jul 2 at 13:15






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

How to add background colour in existing image using Swift?

Moria Casán

How to make file upload 'Required' in Contact Form 7?