Openlayer高阶样式使用
目录
问题来源
因需要要使用到可叠加的openlayer样式,所以在官网的demo中找到两个例子,并从中提炼出我所需的样式基础。
Demo1
这个例子通过style数组来实现叠加型,核心是多写一个用于点的样式并利用geometry属性来套用得到叠加效果。
var styles = [
/* We are using two different styles for the polygons:
* - The first style is for the polygons themselves.
* - The second style is to draw the vertices of the polygons.
* In a custom `geometry` function the vertices of a polygon are
* returned as `MultiPoint` geometry, which will be used to render
* the style.
*/
new ol.style.Style({
stroke: new ol.style.Stroke({
color: 'blue',
width: 3
}),
fill: new ol.style.Fill({
color: 'rgba(0, 0, 255, 0.1)'
})
}),
new ol.style.Style({
image: new ol.style.Circle({
radius: 5,
fill: new ol.style.Fill({
color: 'orange'
})
}),
geometry: function(feature) {
// return the coordinates of the first ring of the polygon
var coordinates = feature.getGeometry().getCoordinates()[0];
return new ol.geom.MultiPoint(coordinates);
}
})
];

Demo2
利用函数来完成特殊的效果,亮点在于使用了段与段的联系来生成每个端点下的样式。
style: function(feature) {
var length = feature.getGeometry().getCoordinates().length;
var styles = [
new ol.style.Style({
stroke: new ol.style.Stroke({
color: 'blue',
width: 3
}),
fill: new ol.style.Fill({
color: 'rgba(0, 0, 255, 0.1)'
})
})
];
geometry.forEachSegment(function(start, end){
styles.push(new ol.style.Style({
geometry: new ol.geom.Point(end),
image: new ol.style.Circle({
radius: 5,
fill: new ol.style.Fill({
color: 'orange'
}),
text:new ol.style.Text({
text:length.toString()
})
}),
}));
});
return styles;
}

改进的应用
本人通过对以上两个例子的理解,利用循环,单独为每个点作独立样式,适用于打造较为酷炫的效果。(核心是增量更新样式,不要重头开始,浪费时间,这里没有写换图形时清空样式的代码,当然也可以不增量更新,毕竟一般的图形点数也不会太多)
var styles = [
new ol.style.Style({
stroke: new ol.style.Stroke({
color: 'blue',
width: 3
}),
fill: new ol.style.Fill({
color: 'rgba(0, 0, 255, 0.1)'
})
})
];
style: function(feature){
var geometry = feature.getGeometry();
var coordinates = geometry.getCoordinates();
for(var i=styles.length-1;i<coordinates.length;i++){
styles.push(new ol.style.Style({
geometry: new ol.geom.Point(coordinates[i]),
image: new ol.style.Circle({
radius: 10,
fill: new ol.style.Fill({
color: 'orange'
})
}),
text:new ol.style.Text({
text:(i+1).toString()
})
}));
}
return styles;
}

转载自:https://blog.csdn.net/u013323965/article/details/56488453