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
})
});
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
})
});
Share
edited Jul 2, 2018 at 9:05
Ignacio Ara
2,5822 gold badges27 silver badges37 bronze badges
asked Jul 1, 2018 at 20:55
Jaahnvi MohanJaahnvi Mohan
711 silver badge3 bronze badges
2 Answers
Reset to default 3I 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);
});
state={
mouePos:[1,2]
}
this.state.map.on('pointermove', (evt)=>{
this.setState({mousePos:[evt.coordinate[0],evt.coordinate[1]]},()=>{
console.log(evt.coordinate)
})
})
You can use mousePos state as a storage i think