我的openlayers 3应用程序在地图上绘制了几个LineString功能(从几十到2000-3000).
当为LineStrings的每个片段设置不同的颜色时,我遇到了巨大的性能影响(从地图上的几个LineStrings开始).变焦和平移完全没有响应,使我的应用程序无法在此表单中使用.
由于我不想为每个段设置一个新几何(但只改变它的颜色),我想有必要有一个更有效的方法来实现这个?
这是我的代码:
var styleFunction = function(feature, resolution) {
var i = 0, geometry = feature.getGeometry();
geometry.forEachSegment(function (start, end) {
color = colors[i];
styles.push(new ol.style.Style({
geometry: new ol.geom.LineString([start, end]),
fill: new ol.style.Fill({
color: color
}),
stroke: new ol.style.Stroke({
color: color,
width: 2
})
}));
i++;
});
return styles;
}
var vectorLayer = new ol.layer.Vector({
source: vectorSource,
style: styleFunction
});
Run Code Online (Sandbox Code Playgroud)
您可以尝试优化一些事项:
缓存填充和描边样式
var fillStyles = colors.map(function(color, i) {
return new ol.style.Fill({
color: color
})
});
var strokeStyles = colors.map(function(color, i) {
return new ol.style.Stroke({
color: color,
width: 2
})
});
Run Code Online (Sandbox Code Playgroud)
缓存每个功能的样式
vectorSource.forEach(function(feature, i) {
var geometry = feature.getGeometry();
var styles = [];
var i = 0;
geometry.forEachSegment(function (start, end) {
styles.push(new ol.style.Style({
geometry: new ol.geom.LineString([start, end]),
fill: fillStyles[i],
stroke: strokeStyles[i]
}));
i++;
});
feature.setStyle(styles);
});
Run Code Online (Sandbox Code Playgroud)
禁用在动画和交互期间更新渲染
var vectorLayer = new ol.layer.Vector({
source: vectorSource,
updateWhileAnimating: false,
updateWhileInteracting: false
});
Run Code Online (Sandbox Code Playgroud)
如果所有这些都无济于事,您可能还需要查看ol.source.ImageVector(示例).
由于我们无法解决问题,即使有 tsauerwein 的建议,这个功能也被暂时搁置了。现在我们带着新的想法回到了这个问题,实际上找到了一个“解决方案”。
我在问题中没有明确说明的是,LineString 的各段根据其起点的属性进行着色。因此,如果此属性的值在多个连续段之间不发生变化,则它们可能会共享相同的颜色。
这个想法是避免为每个片段创建新样式,而是仅在必要时(当颜色更改时)创建新样式:
let i = 0,
color = '#FE2EF7', //pink. should not be displayed
previousColor = '#FE2EF7',
lineString,
lastCoordinate = geometry.getLastCoordinate();
geometry.forEachSegment(((start, end) => {
color = this.getColorFromProperty(LinePoints[i].myProperty);
//First segment
if (lineString == null) {
lineString = new ol.geom.LineString([start, end]);
} else {
//Color changes: push the current segment and start a new one
if (color !== previousColor) {
styles.push(new ol.style.Style({
geometry: lineString,
fill: new ol.style.Fill({
color: previousColor
}),
stroke: new ol.style.Stroke({
color: previousColor,
width: 2
})
}));
lineString = new ol.geom.LineString([start, end]);
} else {
//Color is same: continue the current segment
lineString.appendCoordinate(end);
}
//Last segment
if (end[0] === lastCoordinate[0] && end[1] === lastCoordinate[1]) {
styles.push(new ol.style.Style({
geometry: lineString,
fill: new ol.style.Fill({
color: color
}),
stroke: new ol.style.Stroke({
color: color,
width: 2
})
}));
}
}
previousColor = color;
i++;
}
Run Code Online (Sandbox Code Playgroud)