0

I'm trying to display coordinates of map click event. I do not think the coordinates are displayed correctly. The two numbers shown to me are (3889586.1245487547, 6296722.285457358).

Where do you think the problem comes from?

here is my code:

map.on('click',function(e){
        map.forEachFeatureAtPixel(e.pixel,function(feature , layer){
            let clickedCoordinate = e.coordinate;
            let clickedFeatureCountryName = feature.get('NAME_0');
            let clickedFeatureCityName = feature.get('NAME_1');
            let clickedFeatureAreaName = feature.get('NAME_2');
            let clickedLatitudeCoordinate = clickedCoordinate[1];
            let clickedLongitudeCoordinate = clickedCoordinate[0];
            overlayLayer.setPosition(clickedCoordinate);
            overlayFeatureCountryName.innerHTML = clickedFeatureCountryName;
            overlayFeatureCityName.innerHTML = clickedFeatureCityName;
            overlayFeatureAreaName.innerHTML = clickedFeatureAreaName;
            overlayLatitudeCoordinate.innerHTML=clickedLatitudeCoordinate;
            overlayLongitudeCoordinate.innerHTML=clickedLongitudeCoordinate;
        })
    })
}
2

Really simple. Your map is using EPSG:3857 for projections. It seems you want longitude, latitude. You should do

let xy = ol.proj.toLonLat(clickedCoordinate);
console.log(xy);

Above solution is for standalone Openlayers library, otherwise, when using JavaScript bundlers like Webpack or Parcel, you should do

import {toLonLat} from 'ol/proj';

let xy = toLonLat(clickedCoordinate);
console.log(xy);

See toLonLat API related docs

The examples above do not unpack coordinates. You may prefer

import {toLonLat} from 'ol/proj';

let [x, y] = toLonLat(clickedCoordinate);
console.log(x, y);
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.