1. 程式人生 > >關於Openlayers中自定義滑鼠的移出事件

關於Openlayers中自定義滑鼠的移出事件

才來新公司沒幾天,公司是做WebGis開發的,來公司之後學習了OpenLayers,在遇到自定義事件的時候,發現只有滑鼠移入的自定義事件。
比如下面這樣,之前的黃色的圓下面是紅色的圓,滑鼠放進去之後是程式設計綠色的圓,這裡用的是滑鼠移入的自定義事件,但是滑鼠移出之後再變回原來的事件卻沒有。![滑鼠放進去的時候圓變成綠色](https://img-blog.csdnimg.cn/20181203151053178.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2xvbmdsb25nenVv,size_16,color_FFFFFF,t_70)
在網上查了很多,也沒有找到相關的滿意的答案,後怒查API,終於給我找到了,下面是滑鼠移出之後綠色的圓又變回了紅色的圓

滑鼠移出圓變成原來的紅色 下面不廢話直接上程式碼:
var feature1 = new ol.Feature({
geometry:new ol.geom.Point([104,30])
});

feature1.setStyle(new ol.style.Style({
	image:new ol.style.Circle({
		radius:100,
		fill:new ol.style.Fill({
			color:'red'	
		})	
	})
}));

var feature2 = new ol.Feature({
	geometry:new ol.geom.Point([5000104,5000030])
});

feature2.setStyle(new ol.style.Style({
	image:new ol.style.Circle({
		radius:100,
		fill:new ol.style.Fill({
			color:'yellow'	
		})
	})
}));


var map = new ol.Map({
	interactions:ol.interaction.defaults({
		doubleClickZoom:false,
		mouseWheelZoom:false,
		shiftDragZoom:false
	}),
	layers:[
		new ol.layer.Tile({
			source:new ol.source.OSM()	
		}),
		
		new ol.layer.Vector({
			source:new ol.source.Vector({
				features:[feature1,feature2]
			})
		})
	],	
	
	view:new ol.View({
		//center:[104,30],
		//projection:'EPSG:4326',
		center:[104,30],
		zoom:2
	}),
	target:'map'
});

  map.on('pointermove', function(event){
        if( map.hasFeatureAtPixel(event.pixel)){
			//如果相交,返回相交的圖層,並且觸發方法
		map.forEachFeatureAtPixel(event.pixel, function(feature){
          // 為移動到的feature傳送自定義的mousemove訊息
		  feature.dispatchEvent({type: 'mousein', event: event});
     		});
		}else{
			feature1.setStyle(new ol.style.Style({
				image:new ol.style.Circle({
					radius:100,
					fill:new ol.style.Fill({
						color:'red'
					})	
				})	
			}))	
		}
  });
  //為feature1註冊自定義的監聽事件
  feature1.on('mousein',function(event){
	  this.setStyle(new ol.style.Style({
		image:new ol.style.Circle({
			radius:100,
			fill:new ol.style.Fill({
				color:'green'	
			})
		})	  
	}))
});
不難發現,在這裡 if( map.hasFeatureAtPixel(event.pixel)){
			//如果相交,返回相交的圖層,並且觸發方法
	map.forEachFeatureAtPixel(event.pixel, function(feature)
這兩句程式碼起了很重要的作用,翻閱API我發現,hasFeatureAtPixel這個方法是檢測要素是否與視口上的畫素相交,之後用forEachLayerAtPixel這個方法檢測視口上畫素的顏色值的圖層,並對每個匹配圖層執行回撥。之後再派發自定義事件函式,這樣就實現了滑鼠放入是圓變色,滑鼠移出使圓變回原來的顏色的自定義事件,當然這裡的滑鼠移動回去因為裡面設定的style和之前的一樣,如果設定成其他的顏色就就變成你自己自定義的顏色。
新手第一次發帖,如有錯誤懇請大家指正,歡迎大家的批評指正。