功能描述及問題
大概描述一下我項目的部分需求:1. 自定義地圖的背景圖片 2.添加、刪除一個播放直播流的標記點(用來播放視頻流) 3.添加、刪除用戶自定義標籤標記點
遇到問題
主要是獲取和外部刪除標記點操作中對應的標記點(添加很簡單,主要還是刪除難 畢竟自己也是才搞了一週)。
第一感覺應該獲取地圖中每一個圖層,然後去查看圖層中提供的方式是否又可以區別開的,結果一看只能通過getSource()方法,但獲取的soure缺沒辦法區分(還是自己菜,沒好好理解自己寫的代碼)。
解決方法
遇到問題肯定百度嘍。雖然有時候也很不靠譜。。。
當我看到某個博主寫的一行代碼時 if(source instanceof ol.source.Vector)
時,我突然查看我代碼中每個圖層中layer中source的對象具體是啥,可以根據不同的類型區分你想要區分的。好比我自定義地圖使用的source就是ol.source.ImageStatic對象,而剛好直播流和標籤我使用的source是ol.source.Vector,你也可以根據你這添加到層中的具體source類型來區分。下面就很方面獲取到你設置的相關的自定義屬性,一起的進行相應的操作即可。
部分代碼
map = new ol.Map({
...
layers: [
new ol.layer.Image({
// 自定義圖片圖層
source: new ol.source.ImageStatic({
attributions:
'©<a style="color:red;" href="#">科技</a>',
url: "plugin/openlayers/online_communities.png",
projection: projection_img,
imageExtent: extent
})
})
],
...
});
...
// 需要動態去添加的 標記點的相關代碼
function createLabel() {
var iconFeature = new ol.Feature({
geometry: new ol.geom.Point([300, 300]),
custom: { // 自定屬性
mark: "no1",
type: "label",
name: 'Label自定義內容'
},
population: 4000,
rainfall: 500
});
iconFeature.set(
"style",
createStyle( // 一個自定義設置標記點樣式的函數
"plugin/openlayers/label.png",
undefined
)
);
map.addLayer(
new ol.layer.Vector({
style: function (feature) {
return feature.get("style");
},
source: new ol.source.Vector({ features: [iconFeature] })
})
);
...
// 區分
emap.getLayers().forEach(function(layer){
// 除去背景圖片層
...
var source = layer.getSource();
// 判斷當前source是屬於ol.source.Vector
// 過濾去背景圖片那一快(很重要)
if(source instanceof ol.source.Vector){
var features = source.getFeatures()
var featureLength = features.length;
if(featureLength >0){
for(var labeli = 0;labeli<featureLength;labeli++){
// 下面的是一個操作對象的匹配,是我自己的需求刪除當前圖層
if(features[labeli].get("custom").mark === mark.id){
emap.removeLayer(layer)
}
}
}
}
})
...