动态改变图标
在实际业务应用中,需要根据环境条件,动态的修改图标样式,以反馈数据变化。 比如像下面这样,点击五星,五星图标会用红色填充:
对应的代码如下:
<div id="map" style="width: 100%"></div>
<script type="text/javascript">
var layer = new ol.layer.Vector({
source: new ol.source.Vector()
})
var map = new ol.Map({
layers: [
new ol.layer.Tile({
source: new ol.source.OSM()
}),
layer
],
target: 'map',
view: new ol.View({
projection: 'EPSG:4326',
center: [104, 30],
zoom: 10
})
});
// 添加一个空心的五星
var star = new ol.Feature({
geometry: new ol.geom.Point([104, 30])
});
star.setStyle(new ol.style.Style({
image: new ol.style.RegularShape({
points: 5,
radius1: 20,
radius2: 10,
stroke: new ol.style.Stroke({
color: 'red',
size: 2
})
})
}));
layer.getSource().addFeature(star);
// 监听地图点击事件
map.on('click', function(event){
var feature = map.forEachFeatureAtPixel(event.pixel, function(feature){
return feature;
});
if (feature) {
// 将空心五星为红色实心五星
var style = feature.getStyle().getImage();
feature.setStyle(new ol.style.Style({
image: new ol.style.RegularShape({
points: 5,
radius1: 20,
radius2: 10,
stroke: style.getStroke(),
fill: new ol.style.Fill({
color: 'red'
})
})
}));
}
});
</script>