javascript - 如何从 OSM 中删除标记
问题描述
我正在做一个使用 Open Street Maps 的 Web 应用程序,我正在向它添加一些标记。我需要删除地图上的所有图层。
我已经尝试了一些我在其他问题上找到的例子,但没有一个对我有用。我不确定我是否使用开放层。
这是创建地图的代码:
function initialize_map() {
navigator.geolocation.getCurrentPosition(onSuccess, onError);
map = new ol.Map({
target: "map",
layers: [
new ol.layer.Tile({
source: new ol.source.OSM({
url: "https://a.tile.openstreetmap.org/{z}/{x}/{y}.png"
})
})
],
view: new ol.View({
center: ol.proj.fromLonLat([mapLng, mapLat]),
zoom: mapDefaultZoom
})
});
GetDados();
}
这是我用来添加标记的代码:
function add_map_point(lat, lng) {
var vectorLayer = new ol.layer.Vector({
source: new ol.source.Vector({
features: [new ol.Feature({
geometry: new ol.geom.Point(ol.proj.transform([parseFloat(lng), parseFloat(lat)], 'EPSG:4326', 'EPSG:3857')),
})]
}),
style: new ol.style.Style({
image: new ol.style.Icon({
anchor: [0.5, 0.5],
anchorXUnits: "fraction",
anchorYUnits: "fraction",
src: "https://www.freeiconspng.com/minicovers/bus-driver-icon-png-1.png"
})
})
});
map.addLayer(vectorLayer);
}
解决方案
while (map.getLayers().removeAt(1)) {}
将从地图中删除除索引 0 之外的所有图层,这是您的 OSM 图层。
但是为什么每个标记都需要一个图层呢?如果在初始化地图时创建矢量图层,则只需添加点
function initialize_map() {
navigator.geolocation.getCurrentPosition(onSuccess, onError);
var vectorLayer = new ol.layer.Vector({
source: new ol.source.Vector(),
style: new ol.style.Style({
image: new ol.style.Icon({
anchor: [0.5, 0.5],
anchorXUnits: "fraction",
anchorYUnits: "fraction",
src: "https://www.freeiconspng.com/minicovers/bus-driver-icon-png-1.png"
})
})
});
map = new ol.Map({
target: "map",
layers: [
new ol.layer.Tile({
source: new ol.source.OSM({
url: "https://a.tile.openstreetmap.org/{z}/{x}/{y}.png"
})
}),
vectorLayer
],
view: new ol.View({
center: ol.proj.fromLonLat([mapLng, mapLat]),
zoom: mapDefaultZoom
})
});
GetDados();
}
function add_map_point(lat, lng) {
vectorLayer.getSource().addFeature(
new ol.Feature({
geometry: new ol.geom.Point(ol.proj.transform([parseFloat(lng), parseFloat(lat)], 'EPSG:4326', 'EPSG:3857')),
})
);
}
并且可以轻松清除它们
vectorLayer.getSource().clear();
推荐阅读
- c# - 自定义组合框:防止设计师添加到项目
- c++ - C++ 从另一个函数退出函数
- java - classloader.getResource 返回带有war文件的路径
- java - 问题 >> 如果字符串包含两个或多个字符,则打印“True”或“False”
- sapb1 - 如何知道表中的哪个字段接收变量?
- apache-spark - Spark-shell 无法启动异常:java.lang.reflect.InvocationTargetException
- android - 当将此作为参数传递给类时,表示需要的上下文为空
- javascript - 提交前更改表单属性
- java - @OneToMany 关系不会将父项的主键保存在子表中
- angular - ngx-quill 无法显示下拉标签