写个例子openlayers 更新点击要素的样式
时间: 2023-10-04 16:13:51 浏览: 87
好的,下面是一个完整的例子,实现在点击要素时更新其样式:
```javascript
var vectorSource = new ol.source.Vector({
features: [
new ol.Feature({
geometry: new ol.geom.Point([0, 0]),
name: 'Point 1'
}),
new ol.Feature({
geometry: new ol.geom.Point([10, 10]),
name: 'Point 2'
})
]
});
var vectorLayer = new ol.layer.Vector({
source: vectorSource
});
var map = new ol.Map({
target: 'map',
layers: [
new ol.layer.Tile({
source: new ol.source.OSM()
}),
vectorLayer
],
view: new ol.View({
center: ol.proj.fromLonLat([0, 0]),
zoom: 3
})
});
var selectInteraction = new ol.interaction.Select({
condition: ol.events.condition.click
});
selectInteraction.on('select', function(e) {
var selectedFeatures = e.target.getFeatures();
selectedFeatures.forEach(function(feature) {
feature.setStyle(new ol.style.Style({
stroke: new ol.style.Stroke({
color: 'red',
width: 2
}),
fill: new ol.style.Fill({
color: 'rgba(255, 0, 0, 0.1)'
})
}));
});
});
map.addInteraction(selectInteraction);
```
在这个例子中,我们创建了一个包含两个点要素的矢量图层,并添加了一个 select interaction。当你点击一个要素时,它的样式会被更新为红色的边框和半透明红色的填充。
阅读全文