当我单击标记时,我想获取位置的坐标。我可以得到某个位置的经度和纬度,但是它们与我以前设置时的位置不同
例如,如果我使用latitude:48.879882939225 longitude: 2.3558143608438
设置巴黎的标记,则当我单击同一标记时会收到latitude:49.00659123218202 longitude: 2.2758007269287077
我写这个来设置地图及其标记
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);
如何获得正确的坐标?
最佳答案
在缩放级别6时,标记的宽度将超过0.1度。要获取标记的坐标,请使用类似
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];
}
});