【问题标题】:Set FillColor of MGLFillStyleLayer by color feature attribute通过颜色特征属性设置 MGLFillStyleLayer 的 FillColor
【发布时间】:2019-09-03 07:12:03
【问题描述】:

我们正在开发一个 iOS 应用程序,但在设置 MGLFillStyleLayer (MapBox iOS SDK) 的填充颜色时遇到问题。

我们有一个大的 .geojson 文件,它被解析并添加到标准 MapBox 地图中。 geojson 中的每个特征都有一个“颜色”属性来设置特征的背景颜色。颜色保存为十六进制代码。

是否可以使用 MapBox 表达式或类似“forEach 功能 -> 设置填充颜色”之类的方式单独设置每个功能的颜色?

我们尝试使用 MapBox 为样式提供的表达式 (https://docs.mapbox.com/ios/api/maps/4.1.1/for-style-authors.html) 来更改颜色,但无法弄清楚如何将特征属性加载到 swift-function 中以生成颜色。 在 Mapbox 的热图示例(https://docs.mapbox.com/ios/maps/examples/heatmap-example/)中,我们看到可以通过 NSNumber-Value 设置填充颜色

let colorDictionary: [NSNumber: UIColor] = [
0.0: .clear,
0.01: .white,
0.15: UIColor(red: 0.19, green: 0.30, blue: 0.80, alpha: 1.0),
0.5: UIColor(red: 0.73, green: 0.23, blue: 0.25, alpha: 1.0),
1: .yellow
]

也许我们需要定义一些固定值,比如 1 = #db7851, 2 = .... 等等才能做到这一点?

为了添加geojson数据,我们使用以下代码

let data = try Data(contentsOf: url)

guard let shapeCollectionFeature = try MGLShape(data: data, encoding: String.Encoding.utf8.rawValue) as? MGLShapeCollectionFeature else {
                    fatalError("Could not cast to specified MGLShapeCollectionFeature")
}

// Create source and add it to the map style.
let source = MGLShapeSource(identifier: "flurstuecke_shape", shape: shapeCollectionFeature, options: nil)
style.addSource(source)

let fillLayer = MGLFillStyleLayer(identifier: "flurstuecke", source: source)
style.addLayer(fillLayer)

出于测试目的,我们添加了一个触摸事件来更改所选功能的颜色(仅用于测试 MapBox 表达式)。

let spot = sender.location(in: mapView)
let features = mapView.visibleFeatures(at: spot, styleLayerIdentifiers: Set(["flurstuecke"]))

if let feature = features.first, let fbid = feature.attribute(forKey: "FBID") as? String {
  guard let layer = mapView.style?.layer(withIdentifier: "flurstuecke") as? MGLFillStyleLayer 
else {
  fatalError("Could not cast to specified MGLFillStyleLayer")
}

   layer.fillColor = NSExpression(format: "TERNARY(FBID = %@, %@, %@)", fbid, UIColor.green, UIColor.blue)
}

我们希望有人可以给我们一些提示或一些文档来帮助我们为每个功能着色。谢谢:)

【问题讨论】:

    标签: mapbox-ios


    【解决方案1】:

    使用

    layer.lineColor = NSExpression(forKeyPath: "color")

    geojson 颜色属性值示例: "color"的值可以是:["RGB",255,0,0], "red","#000000"

    【讨论】:

    • 感谢您的帮助。有时候就是这么简单:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多