Lx2pwn
Lx2pwn

Reputation: 323

openlayers doesn't return the correct coordinates

I'm tring to get the coordinate of a location when I click on a marker. I can get latitude and longitude of a location but they aren't the same that I used to set them

For example if i use latitude:48.879882939225 longitude: 2.3558143608438 to set the marker for Paris, when I click on the same marker I receive latitude:49.00659123218202 longitude: 2.2758007269287077

I write this to set the map and its markers

let markers = getMarkers(data);


$('.content').html(
    '<div id="map" class="map" style="height: 100%; width: 100%"></div>'
)

var map = new ol.Map({
    target: 'map',
    layers: [
        new ol.layer.Tile({
            source: new ol.source.OSM()
        })
    ],
    view: new ol.View({
        center: ol.proj.fromLonLat([12.51, 41.89]),
        zoom:6
    })
});

map.on('singleclick', function(evt){
    console.log(ol.proj.transform(evt.coordinate, 'EPSG:3857', 'EPSG:4326'));
    let lat = ol.proj.transform(evt.coordinate, 'EPSG:3857', 'EPSG:4326')[0];
    let lng = ol.proj.transform(evt.coordinate, 'EPSG:3857', 'EPSG:4326')[1];


});

var features = [];

for (var i = 0; i < markers.length; i++) {
    var item = markers[i];
    var longitude = item.lng;
    var latitude = item.lat;

    var iconFeature = new ol.Feature({
        geometry: new ol.geom.Point(ol.proj.transform([longitude, latitude], 'EPSG:4326', 'EPSG:3857'))
    });

    var iconStyle = new ol.style.Style({
        image: new ol.style.Icon(({
            anchor: [0.5, 1],
            src: "http://cdn.mapmarker.io/api/v1/pin?text=P&size=50&hoffset=1"

        }))
    });

    iconFeature.setStyle(iconStyle);
    features.push(iconFeature);

}

var vectorSource = new ol.source.Vector({
    features: features
});

var vectorLayer = new ol.layer.Vector({
    source: vectorSource
});
map.addLayer(vectorLayer);

How can I get the correct coordinate ?

Upvotes: 0

Views: 572

Answers (1)

Mike
Mike

Reputation: 17897

At zoom level 6 your marker will be more than 0.1 degrees wide. To get the coordinates of the marker use something like

map.on('singleclick', function(evt){
  let features = map.getFeaturesAtPixel(evt.pixel);
  if (features.length > 0) {
    let coordinate = features[0].getGeometry().getCoordinates();
    console.log(ol.proj.transform(coordinate, 'EPSG:3857', 'EPSG:4326'));
    let lat = ol.proj.transform(coordinate, 'EPSG:3857', 'EPSG:4326')[0];
    let lng = ol.proj.transform(coordinate, 'EPSG:3857', 'EPSG:4326')[1];
  }
});

Upvotes: 1

Related Questions