vue 写个例子openlayers 更新点击要素的样式
时间: 2023-10-18 14:27:11 浏览: 67
好的,下面是一个 Vue.js 组件的例子,实现在点击要素时更新其样式:
```vue
<template>
<div ref="map" class="map"></div>
</template>
<script>
import 'ol/ol.css';
import Map from 'ol/Map';
import View from 'ol/View';
import TileLayer from 'ol/layer/Tile';
import VectorLayer from 'ol/layer/Vector';
import OSM from 'ol/source/OSM';
import VectorSource from 'ol/source/Vector';
import Feature from 'ol/Feature';
import Point from 'ol/geom/Point';
import Select from 'ol/interaction/Select';
import { Stroke, Style, Fill } from 'ol/style';
export default {
name: 'Map',
mounted() {
const vectorSource = new VectorSource({
features: [
new Feature({
geometry: new Point([0, 0]),
name: 'Point 1'
}),
new Feature({
geometry: new Point([10, 10]),
name: 'Point 2'
})
]
});
const vectorLayer = new VectorLayer({
source: vectorSource,
style: new Style({
image: new CircleStyle({
radius: 5,
fill: new Fill({
color: 'rgba(0, 0, 255, 0.1)'
}),
stroke: new Stroke({
color: 'blue',
width: 2
})
})
})
});
const map = new Map({
target: this.$refs.map,
layers: [
new TileLayer({
source: new OSM()
}),
vectorLayer
],
view: new View({
center: [0, 0],
zoom: 3
})
});
const selectInteraction = new Select({
condition: click
});
selectInteraction.on('select', (e) => {
const selectedFeatures = e.target.getFeatures();
selectedFeatures.forEach((feature) => {
feature.setStyle(new Style({
stroke: new Stroke({
color: 'red',
width: 2
}),
fill: new Fill({
color: 'rgba(255, 0, 0, 0.1)'
})
}));
});
});
map.addInteraction(selectInteraction);
}
};
</script>
<style>
.map {
width: 100%;
height: 400px;
}
</style>
```
在这个例子中,我们创建了一个 Vue.js 组件,其中包含一个包含两个点要素的矢量图层,并添加了一个 select interaction。当你点击一个要素时,它的样式会被更新为红色的边框和半透明红色的填充。注意,在 Vue.js 中,我们使用了 `$refs` 来访问 DOM 元素。
阅读全文