jsapi也有提供高亮的實現接口,但這裏沒用,而用的是一種改變圖形(graphic)樣式的思路javascript
本文實現效果是:地圖有多個面圖形,當鼠標移動到面的上方,面高亮顯示,鼠標移出後高亮解除java
初始化api
//高亮初始化 highlightInit: function () { //添加一個圖形圖層存放要高亮的圖形 let layer = new this.apiInstance.GraphicsLayer({ id: "highlightLayer", //空間參考,通常要跟地圖的同樣 spatialReference: this.mapView.spatialReference, }); //圖層添加到地圖 this.map.add(layer); //添加兩個面 let wkt = "POLYGON((113.527839 22.27028,113.527238 22.2557786,113.5437178 22.2597268,113.54423 22.2730306,113.527839 22.27028))"; let style = { color: [50, 205, 50, 0.2], outline: { color: [255, 0, 0], width: 1 } }; let graphic = mapUtil.geometry.wktToPolygonGraphic(this.apiInstance, wkt, style, this.mapView.spatialReference, null); layer.graphics.add(graphic); wkt = "POLYGON((113.51319 22.26819,113.51473 22.257561,113.520480 22.25747,113.519966 22.26904,113.51319 22.26819))"; graphic = mapUtil.geometry.wktToPolygonGraphic(this.apiInstance, wkt, style, this.mapView.spatialReference, null); layer.graphics.add(graphic); },
監聽鼠標移動事件,這段代碼一般在地圖初始化後執行this
//鼠標移動事件 this.mapView.on("pointer-move", function (event) { this.mapView.hitTest(event).then(function (response) { //鼠標移動到圖形時高亮圖形的實現 //原理:監聽鼠標移動事件,當鼠標移動到某圖形時,就改變改圖形的樣式(高亮實際是換一種更「亮」的樣式),而後鼠標移出圖形,就把圖形樣式恢復回去 //當前鼠標下的圖形,也就是應該高亮的圖形 let pointerFacilityGraphic = null; if (response.results[0]) { //獲取到當前鼠標下方的圖形 var graphic = response.results[0].graphic; if (graphic.layer) { if (graphic.layer.id === "highlightLayer") { //當前鼠標下的圖形,也就是應該高亮的圖形 pointerFacilityGraphic = graphic; } } } //實現高亮圖形效果 if (pointerFacilityGraphic == null && this.highlightFacilityGraphic != null) { //當鼠標下沒有圖形,當前有高亮圖形,把當前高亮的效果去掉 this.setGraphicHighlight(this.highlightFacilityGraphic, false); this.highlightFacilityGraphic = null; } else if (pointerFacilityGraphic != null && this.highlightFacilityGraphic == null) { //當鼠標下有圖形,當前沒有高亮圖形,把鼠標圖形設爲高亮 this.setGraphicHighlight(pointerFacilityGraphic, true); this.highlightFacilityGraphic = pointerFacilityGraphic; } else if (pointerFacilityGraphic != null && this.highlightFacilityGraphic === pointerFacilityGraphic) { //當鼠標下有圖形,且跟當前高亮圖形是同一個,不作任何事 } else if (pointerFacilityGraphic != null && this.highlightFacilityGraphic !== pointerFacilityGraphic) { //當鼠標下有圖形,且跟當前高亮圖形不一樣一個,把鼠標圖形設爲高亮,把當前高亮的效果去掉 this.setGraphicHighlight(this.highlightFacilityGraphic, false); this.setGraphicHighlight(pointerFacilityGraphic, true); this.highlightFacilityGraphic = pointerFacilityGraphic; } }.bind(this)) }.bind(this));
設置圖層高亮spa
//設置圖形高亮效果 //參數1:圖形 //參數2:是否高亮 setGraphicHighlight: function (graphic, isHighlight) { //基礎樣式 //本例中,正常樣式的填充透明度是0.2,高亮時透明度0.7 let style = { type: "simple-fill", color: [50, 205, 50, 0.2], outline: { color: [255, 0, 0], width: 1 } }; if (isHighlight) { //高亮 style.color = [50, 205, 50, 0.7]; graphic.symbol = style; } else { //不高亮 style.color = [50, 205, 50, 0.2]; graphic.symbol = style; } },