如何将视图添加到地图框样式而不是图像

时间:2019-07-19 17:47:14

标签: ios swift xcode dictionary mapbox

我正在创建一个在地图框mapView上具有图钉的应用。为了使销钉在彼此靠近时能够聚类,我必须将销钉创建为MGLSymbolStyleLayers。但是,这些图层仅允许添加图像,而不能添加视图。有什么办法可以使图层显示视图而不是图像?

 func mapView(_ mapView: MGLMapView, didFinishLoading style: MGLStyle) {
    // Define an initial icon to help set source attributes
    let icon = UIImage(named: "squircle")!

    let pointFeature = MGLPointFeature()
    pointFeature.coordinate = CLLocationCoordinate2D(latitude: 30, longitude: -73)
    let pointFeatureTwo = MGLPointFeature()
    pointFeatureTwo.coordinate = CLLocationCoordinate2D(latitude: 33.4, longitude: -73.4)

    let source = MGLShapeSource(identifier: "id", features: [pointFeature, pointFeatureTwo], options: [.clustered: true, .clusterRadius: icon.size.width/3])
    style.addSource(source)



    let markerLayer = MGLSymbolStyleLayer(identifier: "ports", source: source)
    markerLayer.iconImageName = NSExpression(forConstantValue: "marker")
    markerLayer.predicate = NSPredicate(format: "cluster != YES")
    style.setImage(UIImage(named: "marker")!, forName: "marker")
    markerLayer.iconAllowsOverlap = NSExpression(forConstantValue: "YES")

    let clusterLayer = MGLSymbolStyleLayer(identifier: "clusteredPortsNumbers", source: source)
    clusterLayer.iconAllowsOverlap = NSExpression(forConstantValue: "YES")
    clusterLayer.textColor = NSExpression(forConstantValue: UIColor.white)
    clusterLayer.textFontSize = NSExpression(forConstantValue: NSNumber(value: Double(icon.size.width) / 2))
    clusterLayer.iconAllowsOverlap = NSExpression(forConstantValue: true)
    clusterLayer.textOffset = NSExpression(forConstantValue: CGVector(dx: 0, dy: -0.2))
    clusterLayer.predicate = NSPredicate(format: "cluster == YES")

    // Style image clusters
    style.setImage(UIImage(named: "squircle")!, forName: "squircle")
    style.setImage(UIImage(named: "circle")!, forName: "circle")
    style.setImage(UIImage(named: "rectangle")!, forName: "rectangle")
    style.setImage(UIImage(named: "star")!, forName: "star")
    style.setImage(UIImage(named: "oval")!, forName: "oval")


    let stops = [
        10: NSExpression(forConstantValue: "circle"),
        25: NSExpression(forConstantValue: "rectangle"),
        75: NSExpression(forConstantValue: "star"),
        150: NSExpression(forConstantValue: "oval")
    ]

    // Use expressions to set each cluster's image based on defined stops and display the point count over the corresponding image
    let defaultShape = NSExpression(forConstantValue: "squircle")

    clusterLayer.iconImageName = NSExpression(format: "mgl_step:from:stops:(point_count, %@, %@)", defaultShape, stops)
    clusterLayer.text = NSExpression(format: "CAST(point_count, 'NSString')")

    style.addLayer(markerLayer)
    style.addLayer(clusterLayer)
}

0 个答案:

没有答案