arcgis jsapi接口入门系列(10):图形高亮
图形高亮
jsapi也有提供高亮的实现接口,但这里没用,而用的是一种改变图形(graphic)样式的思路
本文实现效果是:地图有多个面图形,当鼠标移动到面的上方,面高亮显示,鼠标移出后高亮解除
初始化
//高亮初始化
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.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));
设置图层高亮
//设置图形高亮效果
//参数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;
}
},