【OpenLayers笔记】实现鼠标放置在要素上面即可选中要素
首先我们先导入Condition
import {mouseOnly} from "ol/events/condition";
实例化一个Select对象之后设置condition属性,值为上面导入的mouseOnly:
let select = new Select({ condition: mouseOnly, }); map.addInteraction(select);
例子:实现绘制两个多边形然后开启要素选择功能:
//新增一个绘制图形的矢量图层 const vector = new VectorLayer({ source: new VectorSource({ useSpatialIndex: false }), style: { "fill-color": "rgba(255, 255, 255, 0.2)", "stroke-color": "#ffcc33", "stroke-width": 2, "circle-radius": 7, "circle-fill-color": "#ffcc33", }, }); //新增一个绘制图形的交互组件 let draw = new Draw({ //放置一个source(要素需要放到Source里) source: vector.getSource(), //绘制多边形 type: "Polygon", }); let select = new Select({ condition: mouseOnly, }); //添加一个选择器 map.addInteraction(select); //开始先绘图,所以禁用选择功能 select.setActive(false); //要素选择监听 select.on("select", function (event) { console.log("已选中Feature", event.selected); }); //绘制图形计数器 let count = 0; //一个图形绘制结束时的回调方法 draw.on("drawend", function (event) { count++; //当已经绘制完两个之后,禁用图形绘制功能,以及开启选择功能 if (count > 1) { draw.setActive(false); select.setActive(true); } }); //把绘制多边形交互实例放置到 map.addInteraction(draw); //添加矢量图层到map上 map.addLayer(vector);
效果图: