Search code examples
javascriptopenlayers

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

Solution

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