更新 deckLayer 类

This commit is contained in:
JIANG
2025-11-24 15:09:37 +08:00
parent 15e80f105e
commit b4aef962dd
5 changed files with 309 additions and 227 deletions

View File

@@ -67,6 +67,14 @@ export class DeckLayer extends Layer {
// 添加图层
addDeckLayer(layer: any): void {
const currentLayers = this.getDeckLayers();
// 如果已有同 id 图层,则替换保持顺序;否则追加
const idx = currentLayers.findIndex((l: any) => l && l.id === layer.id);
if (idx >= 0) {
const copy = [...currentLayers];
copy[idx] = layer;
this.deck.setProps({ layers: copy });
return;
}
this.deck.setProps({ layers: [...currentLayers, layer] });
}
@@ -85,15 +93,41 @@ export class DeckLayer extends Layer {
return layers.find((layer: any) => layer && layer.id === layerId);
}
// 更新特定图层
updateDeckLayer(layerId: string, props: any): void {
// 更新特定图层:支持传入一个新的 Layer 实例或一个 props 对象
// - 如果传入的是 Layer 实例,则直接替换同 id 的图层为该实例
// - 如果传入的是 props普通对象则基于原图层调用 clone(props)
updateDeckLayer(layerId: string, layerOrProps: any): void {
const layers = this.getDeckLayers();
const updatedLayers = layers.map((layer: any) => {
if (layer && layer.id === layerId) {
return layer.clone(props);
if (!layer || layer.id !== layerId) return layer;
// 如果传入的是一个 deck.gl Layer 实例(通常包含 id 和 props
if (
layerOrProps &&
typeof layerOrProps === "object" &&
layerOrProps.id !== undefined &&
typeof layerOrProps.clone === "function"
) {
// 替换为新的 layer 实例
return layerOrProps;
}
// 否则假定传入的是 props 对象,使用现有 layer.clone(props) 创建新实例
try {
return layer.clone(layerOrProps);
} catch (err) {
// 如果 clone 失败,作为降级策略尝试手动复制 props 到新对象(保留原 layer
// 这通常不应该发生,但保证不会抛出而破坏整个 layers 列表
const newLayer = layer.clone
? layer.clone(layerOrProps)
: {
...layer,
props: { ...(layer.props || {}), ...(layerOrProps || {}) },
};
return newLayer;
}
return layer;
});
this.deck.setProps({ layers: updatedLayers });
}
@@ -113,7 +147,16 @@ export class DeckLayer extends Layer {
// 存储用户设置的可见性
this.userVisibility.set(layerId, visible);
// 更新图层(注意:实际的 visible 可能还受其他条件控制)
this.updateDeckLayer(layerId, { visible });
// 优先尝试使用传入的 layer 实例替换,否则使用 clone({ visible }) 来保留图层类型
const found = this.getDeckLayerById(layerId);
if (!found) return;
try {
// 使用 clone 来确保保持同类型实例
this.updateDeckLayer(layerId, { ...found.props, visible });
} catch (err) {
// 降级:直接替换属性
this.updateDeckLayer(layerId, { visible });
}
// 触发回调通知外部
if (this.onVisibilityChange) {
this.onVisibilityChange(layerId, visible);