vue 写个例子openlayers 更新点击按钮,更新某个要素的样式
时间: 2024-03-17 18:42:18 浏览: 103
好的,以下是一个简单的示例代码:
在 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 VectorLayer from 'ol/layer/Vector';
import VectorSource from 'ol/source/Vector';
import { Circle as CircleStyle, Fill, Stroke, Style } from 'ol/style';
import { Select } from 'ol/interaction';
import { click } from 'ol/events/condition';
```
然后在组件的 `mounted` 钩子函数中初始化地图和交互:
```javascript
mounted() {
const vectorSource = new VectorSource();
const vectorLayer = new VectorLayer({
source: vectorSource,
style: new Style({
image: new CircleStyle({
radius: 10,
fill: new Fill({
color: '#ff0000'
}),
stroke: new Stroke({
color: '#000000',
width: 2
})
})
})
});
const map = new Map({
target: 'map',
layers: [
new TileLayer({
source: new OSM()
}),
vectorLayer
],
view: new View({
center: [0, 0],
zoom: 2
})
});
const select = new Select({
condition: click
});
map.addInteraction(select);
select.on('select', (e) => {
const selectedFeature = e.selected[0];
if (selectedFeature) {
selectedFeature.setStyle(new Style({
image: new CircleStyle({
radius: 10,
fill: new Fill({
color: '#0000ff'
}),
stroke: new Stroke({
color: '#000000',
width: 2
})
})
}));
}
});
const updateButton = document.getElementById('update-button');
updateButton.addEventListener('click', () => {
const selectedFeature = select.getFeatures().getArray()[0];
if (selectedFeature) {
selectedFeature.setStyle(new Style({
image: new CircleStyle({
radius: 10,
fill: new Fill({
color: '#00ff00'
}),
stroke: new Stroke({
color: '#000000',
width: 2
})
})
}));
}
});
}
```
这段代码会在页面中渲染一个地图,并且添加一个 `Select` 交互,用于监视鼠标点击事件并且更新点击要素的样式。当你点击地图上的要素时,其样式会从红色变成蓝色。此外,我们还添加了一个按钮来更新选定要素的样式,将其从蓝色变成绿色。
阅读全文