Leaflet使用switch动态添加LayerGroup到图层控件报错问询
问题根源
你遇到的报错完全是因为newPoint函数的返回值类型错误导致的:
- 只有case 20返回的是真实的
L.layerGroup实例对象,其他所有case返回的都是字符串(比如'point_B'、'point_C') - 字符串本身没有
addLayer方法,addTo方法内部会调用目标对象的addLayer,自然就抛出了TypeError: t.addLayer is not a function的错误
修复方法
第一步:修正newPoint函数的返回值
把newPoint函数中所有case返回值的引号全部删掉,直接返回对应的layerGroup变量即可,同时补充default分支避免未匹配的typeId导致返回undefined:
function newPoint(t){ switch (t){ case 20: return point_A; case 21: return point_B; case 22: return point_C; case 29: return point_D; case 30: return point_E; case 34: return point_F; case 40: return point_G; case 49: return point_H; case 56: return point_I; case 58: return point_J; case 66: return point_K; case 69: return point_L; case 99: return point_M; case 100: return point_N; default: return point_A; // 可根据自己的需求调整默认归属的图层组 } };
第二步(可选优化):替换所有switch为映射表,代码更易维护
你目前的多个switch函数可以统一用对象映射实现,不需要写大量冗余的分支判断,示例如下:
// 统一配置typeId对应的所有参数 const typeConfig = { 20: {layer: point_A, shape: 'circle', radius: 10, weight: 2, color: '#ffffff', fillColor: '#0000ff'}, 21: {layer: point_B, shape: 'circle', radius: 8, weight: 2, color: '#ffffff', fillColor: '#ffffff'}, // 剩下的所有typeId按照上面的格式补全即可 99: {layer: point_M, shape: 'x', radius: 12, weight: 3, color: '#ff0000', fillColor: '#ff0000'}, 100: {layer: point_N, shape: 'circle', radius: 5, weight: 2, color: '#ffffff', fillColor: '#ff0000'} } // 调用的时候直接取配置即可 pointToLayer: function(feature, latlng) { const id = feature.properties.typeId; const config = typeConfig[id] || typeConfig[20]; // 没匹配到就用默认配置 return new L.shapeMarker(latlng, { radius: config.radius, fillColor: config.fillColor, fillOpacity: 1, color: config.color, weight: config.weight, shape: config.shape }).addTo(config.layer); }
第三步:将图层组添加到图层控件
如果要在图层控件中显示这些分组,后续需要把所有layerGroup注册到图层控件中:
const overlayMaps = { "分组A": point_A, "分组B": point_B, // 补全剩下的分组即可 } L.control.layers(baseMaps, overlayMaps).addTo(map);
内容的提问来源于stack exchange,提问作者QGIS-user
相关产品推荐
相关产品推荐

