Skip to main content

SwiftUI版での制約: ForEach で Annotation 作成は対応していない

問題点: ForEach は動作しない

このように書けることを期待したが、対応していない

swift
ForEach(waypoints, id: \.id) { point in
CircleAnnotation(centerCoordinate: point.coord)
.circleRadius(5)
.circleColor(.green)
}

回避1: UIKit で対応(不採用)

  • UIKit 版なら、AnnotationManager の配列に足すだけなので可能

こんな感じ(試してない)

swift
let manager = mapView.annotations.makeCircleAnnotationManager()
manager.annotations = waypoints.map {
var ann = CircleAnnotation(centerCoordinate: $0.coord)
ann.circleRadius = 5
ann.circleColor = .green
return ann
}

→ ただ、これだけのために UIKit版 にしたくないので いまのところ不採用

回避2: 動的にレイヤを作成(採用)

  • GeoJSONSource を自前で作って、レイヤとして足す
  • 回避策と言いつつ、こっちの方がより「Mapboxらしい」書き方かも
swift
let features = waypoints.map { point in
Feature(geometry: .point(Point(point.coord)))
}
GeoJSONSource(id: "waypoints")
.data(.featureCollection(FeatureCollection(features: features)))

CircleLayer(id: "waypointsPin", source: "waypoints")
.circleRadius(5)
.circleColor(UIColor.green)