在实际情况中当遇见大量数据时openlyer加载会特别慢可以使用单图层批量加载 + 样式缓存 + 简化(在低缩放级别)
drawList: [],
tailwaterLayer: null,
tailwaterStyleCache: {},
drawTailwaterArea(data) {
const that = this;
if (!Array.isArray(data) || data.length === 0) {
if (that.tailwaterLayer && that.tailwaterLayer.getSource) {
that.tailwaterLayer.getSource().clear(true);
}
that.drawList = [];
return;
}
if (!that.tailwaterLayer) {
that.tailwaterStyleCache = {};
that.tailwaterLayer = new VectorLayer({
source: new VectorSource(),
zIndex: 9999,
visible: true,
updateWhileAnimating: false,
updateWhileInteracting: false,
declutter: true,
// 样式函数:基于要素属性返回缓存的样式对象
style: function(feature, resolution) {
const params = feature.get("params") || {};
const key = `${params.pondType}_${params.farmType}`;
if (!that.tailwaterStyleCache[key]) {
const c = {
color1: "rgba(85, 147, 255, 1)",
color2: "rgba(85, 147, 255, 0.7)"
}
that.tailwaterStyleCache[key] = new Style({
stroke: new Stroke({
color: c.color1,
width: 2
}),
fill: new Fill({
color: c.color2
})
});
}
return that.tailwaterStyleCache[key];
}
});
if (that.map && that.map.addLayer) {
that.map.addLayer(that.tailwaterLayer);
}
} else {
// 复用已有图层:先清空要素
that.tailwaterLayer.getSource().clear(true);
// 如果该图层之前被移除(例如外部通过 map.removeLayer),确保重新添加到地图
try {
const layers =
that.map && that.map.getLayers && that.map.getLayers().getArray();
if (
that.map &&
Array.isArray(layers) &&
layers.indexOf(that.tailwaterLayer) === -1
) {
that.map.addLayer(that.tailwaterLayer);
}
} catch (e) {
if (that.map && that.map.addLayer) {
that.map.addLayer(that.tailwaterLayer);
}
}
}
// 记录单图层到 drawList(保持外部代码兼容性)
that.drawList = [that.tailwaterLayer];
const format = new GeoJSON();
const features = [];
const currentZoom =
that.map && that.map.getView ? that.map.getView().getZoom() : null;
data.forEach(item => {
if (!item || !item.pondGeomJson) return;
try {
const feature = format.readFeature(item.pondGeomJson);
feature.set("params", { ...item });
// 可选:在较小缩放级别上进行几何简化以减少顶点
if (currentZoom !== null && currentZoom < 12) {
try {
const geom = feature.getGeometry();
if (geom && typeof geom.simplify === "function") {
// tolerance 可根据需要调整
const tolerance = 0.00005 * Math.pow(2, 12 - currentZoom);
const simplified = geom.simplify(tolerance, true);
feature.setGeometry(simplified);
}
} catch (e) {
}
}
features.push(feature);
} catch (e) {
}
});
// 批量加入要素(比逐个 addFeature 更高效)
if (features.length) {
that.tailwaterLayer.getSource().addFeatures(features);
}
},

被折叠的 条评论
为什么被折叠?



