openLayers 添加多个不同类型的图层时 如何选择对应的图层

功能描述及问题

大概描述一下我项目的部分需求: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)
								}
							}
						}
					}
				})
				...

猜你喜欢

转载自blog.csdn.net/u013270347/article/details/105831935