[英]Building a conditional expression using the Mapbox iOS SDK
我正在更新使用 Mapbox v6 SDK 的现有 iOS 应用程序。 该应用程序使用点要素数组定义形状源,并指定应根据特定半径对点进行聚类。 这是执行此操作的代码:
let source = MGLShapeSource(identifier: sourceIdentifier, features: features, options: [.clustered: true, .clusterRadius: 50.0, .maximumZoomLevelForClustering: 14.0])
我还定义了一个圆形样式层来显示 map 上的集群:
let circularClusterLayer = MGLCircleStyleLayer(identifier: "clusteredMarkers", source: source)
circularClusterLayer.predicate = NSPredicate(format: "cluster == YES")
这按预期工作,但现在我需要根据位于集群中的所有特征的属性来定义圆圈颜色。 具体来说,我的每个功能在其名为.needsHelp
的属性字典中都有一个 boolean 属性。 我正在尝试根据此逻辑定义群集标记的圆圈颜色:
if any of the features in the cluster have .needsHelp == true {
// set the circle color = UIColor.red
circularClusterLayer.circleColor = NSExpression(forConstantValue: UIColor.red)
} else {
// set the circle color = UIColor.gray
circularClusterLayer.circleColor = NSExpression(forConstantValue: UIColor.gray)
}
我很确定我应该能够构建一个表达式,如果集群中的任何功能具有.needsHelp == true
则返回 true,否则返回 false。 而且我相信这个表达式将被分配给源的 .clusterProperties 选项,如下所示:
let expression1 = NSExpression(mglJSONObject: ["any", ["==", ["boolean", ["get", "isInEmergency"]], true]])
let expression2 = NSExpression(forConstantValue: UIColor.red)
let clusterPropertyDictionary: NSDictionary = ["clusterContainsFeatureThatNeedsHelp" : [expression1, expression2]]
let selectedContactsSource = MGLShapeSource(identifier: sourceIdentifier, features: features, options: [.clustered: true, .clusterRadius: 50.0, .maximumZoomLevelForClustering: 14.0, .clusterProperties: clusterPropertyDictionary])
我一直在查看Mapbox 表达式指南,我认为我应该使用“任何”决策表达式来获取 boolean 值,指示是否有任何功能具有.needsHelp == true
。 但到目前为止,我一直无法将类似 LISP 的表达式语法翻译成有效的 NSExpression。
我假设除了上面的表达式之外,我还需要另一个表达式来检查“clusterContainsFeatureThatNeedsHelp”的值,然后相应地设置圆圈颜色。 我最好的猜测是它看起来像这样:
// TODO: check value of clusterContainsFeatureThatNeedsHelp to determine circle color
circularClusterLayer.circleColor = NSExpression(forConditional: NSPredicate(format: "%K == %@", "clusterContainsFeatureThatNeedsHelp", NSNumber(value: true)), trueExpression: NSExpression(forConstantValue: UIColor.red), falseExpression: NSExpression(forConstantValue: UIColor.gray))
不幸的是,我没有成功构建这些 NSExpressions 中的任何一个。 有没有人做过这样的事情? 如果是这样,我将不胜感激任何提示或建议!
我终于得到了这个工作。 我现在正在创建这样的 clusterPropertyDictionary:
let firstExpression = NSExpression(format: "max:({$featureAccumulated, clusterContainsFeatureThatNeedsHelp})")
let secondExpression = NSExpression(format: "CAST(needsHelp, 'NSNumber')")
let clusterPropertiesDictionary = ["clusterContainsFeatureThatNeedsHelp" : [firstExpression, secondExpression]]
实际设置圆圈颜色的表达式如下所示:
let expressionForClusterCircleColor = NSExpression(
forConditional: NSPredicate(format: "clusterContainsFeatureThatNeedsHelp > 0"),
trueExpression: NSExpression(forConstantValue: UIColor.red),
falseExpression: NSExpression(forConstantValue: UIColor.gray)
)
circularClusterLayer.circleColor = expressionForClusterCircleColor
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.