vue 写个例子openlayers 监视 slinglick 更新点击要素的样式
时间: 2024-03-17 09:42:16 浏览: 42
好的,以下是一个简单的示例代码:
在 vue 组件中引入 openlayers 和相关样式:
```javascript
import 'ol/ol.css';
import Map from 'ol/Map';
import View from 'ol/View';
import TileLayer from 'ol/layer/Tile';
import OSM from 'ol/source/OSM';
import Select from 'ol/interaction/Select';
import { click } from 'ol/events/condition';
import { Style, Fill, Stroke } from 'ol/style';
import { Circle as CircleStyle } from 'ol/style';
```
然后在组件的 `mounted` 钩子函数中初始化地图和交互:
```javascript
mounted() {
const map = new Map({
target: 'map',
layers: [
new TileLayer({
source: new OSM()
})
],
view: new View({
center: [0, 0],
zoom: 2
})
});
const select = new Select({
condition: click,
style: new Style({
image: new CircleStyle({
radius: 10,
fill: new Fill({
color: 'rgba(255, 255, 255, 0.5)'
}),
stroke: new Stroke({
color: '#ff0000',
width: 2
})
})
})
});
select.on('select', (e) => {
e.target.getFeatures().forEach((feature) => {
feature.setStyle(new Style({
image: new CircleStyle({
radius: 10,
fill: new Fill({
color: 'rgba(0, 0, 255, 0.5)'
}),
stroke: new Stroke({
color: '#0000ff',
width: 2
})
})
}));
});
});
map.addInteraction(select);
}
```
这段代码会在页面中渲染一个地图,并且添加一个 `Select` 交互,用于监视鼠标点击事件并且更新点击要素的样式。当你点击地图上的要素时,其样式会从红色变成蓝色。
阅读全文