我的问题很简单:如何在特定的经度和纬度添加标记?
通过开放层进行工作 example page我创建了一张带有标记的新 map 。
我使用new ol.Feature
添加了标记,但似乎无论我设置什么,标记位置的坐标都不会改变。
请问有人可以就 map 标记未显示在正确位置的原因提供建议吗?
const iconFeature = new ol.Feature({
geometry: new ol.geom.Point([53, -2]), //This marker will not move.
name: 'Somewhere',
});
const map = new ol.Map({
target: 'map',
layers: [
new ol.layer.Tile({
source: new ol.source.OSM(),
}),
new ol.layer.Vector({
source: new ol.source.Vector({
features: [iconFeature]
}),
style: new ol.style.Style({
image: new ol.style.Icon({
anchor: [0.5, 46],
anchorXUnits: 'fraction',
anchorYUnits: 'pixels',
src: 'https://openlayers.org/en/latest/examples/data/icon.png'
})
})
})
],
view: new ol.View({
center: ol.proj.fromLonLat([53,-2]),
zoom: 6
})
});
.map {
width: 100%;
height: 400px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.1.1/build/ol.js"></script>
<div id="map" class="map">
<div id="popup"></div>
</div>
最佳答案
您可以使用 ol.proj.fromLonLat 将 EPSG:4326
转换为 EPSG:3857
,以获取功能并将 map 居中。一般来说,您必须这样做,因为默认投影是 EPSG:3857
。
对于图标:
const iconFeature = new ol.Feature({
geometry: new ol.geom.Point(ol.proj.fromLonLat([-2, 53])),
name: 'Somewhere near Nottingham',
});
将 View / map 置于同一位置中心:
view: new ol.View({
center: ol.proj.fromLonLat([-2, 53]),
zoom: 6
})
工作代码片段:
const iconFeature = new ol.Feature({
geometry: new ol.geom.Point(ol.proj.fromLonLat([-2, 53])),
name: 'Somewhere near Nottingham',
});
const map = new ol.Map({
target: 'map',
layers: [
new ol.layer.Tile({
source: new ol.source.OSM(),
}),
new ol.layer.Vector({
source: new ol.source.Vector({
features: [iconFeature]
}),
style: new ol.style.Style({
image: new ol.style.Icon({
anchor: [0.5, 46],
anchorXUnits: 'fraction',
anchorYUnits: 'pixels',
src: 'https://openlayers.org/en/latest/examples/data/icon.png'
})
})
})
],
view: new ol.View({
center: ol.proj.fromLonLat([-2, 53]),
zoom: 6
})
});
html, body {
width: 100%;
height: 100%;
padding: 0px;
margin: 0px;
}
.map {
width: 100%;
height: 100%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@main/dist/en/v6.14.1/css/ol.css" type="text/css">
<script src="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@main/dist/en/v6.14.1/build/ol.js"></script>
<div id="map" class="map">
<div id="popup"></div>
</div>
关于javascript - 将 map 标记添加到 Open Layers 6,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59720237/