如何在ArcGIS JavaScript API中基于双字段使用uniqueValues
如何使用ArcGIS JavaScript API 4.24按多字段分组统计要素计数?
问题描述
我正在使用ArcGIS JavaScript API 4.24,通过esri/smartMapping/statistics/uniqueValues工具获取FeatureLayer(代码中为fcLayer)内的要素计数,当前代码仅基于AppType单字段实现,示例代码如下:
uniqueValues({ layer: fcLayer, field: "AppType", }).then(function(response) { let infos = response.uniqueValueInfos; infos.forEach(function(info) { console.log("Application Type: ", info.value, " are: ", info.count); }); });
现在需要优化代码,实现按AppType和AppStat两个字段分组查询,但尝试用sqlExpression或sqlWhere替代field参数(比如sqlExpression = "AppType = 'RD' AND AppStat = 'active'")时没有返回结果,求正确实现方式。
解决方案
esri/smartMapping/statistics/uniqueValues工具仅支持基于单字段或单个SQL表达式的唯一值统计,你之前的错误在于将过滤条件当成了分组表达式。要实现多字段分组,需将两个字段组合成唯一标识作为统计依据,以下是两种可行方案:
方法1:通过sqlExpression拼接字段
用SQL表达式把AppType和AppStat拼接成一个唯一字符串,作为统计的基准,每个字段组合会被统计为独立项:
uniqueValues({ layer: fcLayer, sqlExpression: "CONCAT(AppType, '|', AppStat)", // 用分隔符拼接,避免字段值连在一起产生歧义 // 如需额外过滤要素,可添加sqlWhere,比如 sqlWhere: "AppStat = 'active'" }).then(function(response) { let infos = response.uniqueValueInfos; infos.forEach(function(info) { // 将拼接值拆分为原字段 const [appType, appStat] = info.value.split('|'); console.log(`Application Type: ${appType}, Status: ${appStat}, Count: ${info.count}`); }); });
注意:不同数据源的字符串拼接函数有差异,ArcGIS Server托管图层推荐用CONCAT,Oracle用||,SQL Server用+,按需调整。
方法2:用queryFeatures手动统计
若觉得拼接字段不够直观,可直接查询所有要素,在前端手动按双字段分组统计:
fcLayer.queryFeatures({ outFields: ["AppType", "AppStat"], returnGeometry: false // 无需几何信息,提升查询效率 }).then(function(results) { const countMap = new Map(); results.features.forEach(feature => { const key = `${feature.attributes.AppType}|${feature.attributes.AppStat}`; countMap.set(key, (countMap.get(key) || 0) + 1); }); // 遍历输出统计结果 countMap.forEach((count, key) => { const [appType, appStat] = key.split('|'); console.log(`Application Type: ${appType}, Status: ${appStat}, Count: ${count}`); }); });
这种方式更灵活,适合复杂统计场景,但要素量较大时优先选方法1(服务端统计减少前端数据传输)。
内容的提问来源于stack exchange,提问作者Suffii
相关产品推荐
相关产品推荐

