Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
translate ▾

Modern-Apps.git / apple / FindFamily / FindFamilyiOS / UI / MapContainer.swift

MapContainer.swift189 lines · 7.5 KiBRaw
1import SwiftUI
2import MapKit
3
4/// Wraps an `MKMapView` to show user pins, waypoint circles, and to expose camera + tap callbacks.
5struct MapContainer: UIViewRepresentable {
6 let users: [User]
7 let latestLocations: [Int64: LocationValue]
8 let waypoints: [Waypoint]
9 let selectedUserId: Int64?
10 let selectedWaypoint: (coord: Coord, range: Double)?
11 let historicalPosition: Coord?
12 let onUserTap: (Int64) -> Void
13 let onMapTap: () -> Void
14 let onCenterChanged: (Coord) -> Void
15 let animateToCoord: Coord?
16
17 func makeUIView(context: Context) -> MKMapView {
18 let map = MKMapView()
19 map.delegate = context.coordinator
20 map.showsUserLocation = true
21 map.register(UserAnnotationView.self, forAnnotationViewWithReuseIdentifier: "user")
22 map.register(WaypointAnnotationView.self, forAnnotationViewWithReuseIdentifier: "waypoint")
23 let tap = UITapGestureRecognizer(target: context.coordinator, action: #selector(Coordinator.handleTap(_:)))
24 tap.delegate = context.coordinator
25 map.addGestureRecognizer(tap)
26 return map
27 }
28
29 func updateUIView(_ map: MKMapView, context: Context) {
30 // Sync annotations
31 let allUserAnnotations = users.compactMap { u -> UserAnnotation? in
32 guard let loc = historicalPosition.flatMap({ selectedUserId == u.id ? $0 : latestLocations[u.id]?.coord }) ?? latestLocations[u.id]?.coord else { return nil }
33 return UserAnnotation(user: u, coord: loc)
34 }
35 let waypointAnnotations = waypoints.map { WaypointAnnotation(waypoint: $0) }
36
37 let existing = map.annotations.filter { !($0 is MKUserLocation) }
38 map.removeAnnotations(existing)
39 map.addAnnotations(allUserAnnotations)
40 map.addAnnotations(waypointAnnotations)
41
42 // Circle overlays for waypoint ranges + selected waypoint preview.
43 map.removeOverlays(map.overlays)
44 for wp in waypoints {
45 let circle = MKCircle(center: wp.coord.clLocationCoordinate, radius: wp.range)
46 circle.title = "wp"
47 map.addOverlay(circle)
48 }
49 if let sw = selectedWaypoint, sw.range > 0 {
50 let circle = MKCircle(center: sw.coord.clLocationCoordinate, radius: sw.range)
51 circle.title = "selected"
52 map.addOverlay(circle)
53 }
54
55 if let target = animateToCoord {
56 let region = MKCoordinateRegion(
57 center: target.clLocationCoordinate,
58 latitudinalMeters: 2000, longitudinalMeters: 2000
59 )
60 map.setRegion(region, animated: true)
61 }
62 }
63
64 func makeCoordinator() -> Coordinator { Coordinator(parent: self) }
65
66 final class Coordinator: NSObject, MKMapViewDelegate, UIGestureRecognizerDelegate {
67 let parent: MapContainer
68 init(parent: MapContainer) { self.parent = parent }
69
70 func mapView(_ mapView: MKMapView, viewFor annotation: any MKAnnotation) -> MKAnnotationView? {
71 if let u = annotation as? UserAnnotation {
72 let v = mapView.dequeueReusableAnnotationView(withIdentifier: "user", for: u) as! UserAnnotationView
73 v.configure(with: u.user)
74 return v
75 } else if let w = annotation as? WaypointAnnotation {
76 let v = mapView.dequeueReusableAnnotationView(withIdentifier: "waypoint", for: w) as! WaypointAnnotationView
77 v.configure(with: w.waypoint)
78 return v
79 }
80 return nil
81 }
82
83 func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
84 if let u = view.annotation as? UserAnnotation {
85 mapView.deselectAnnotation(view.annotation, animated: false)
86 parent.onUserTap(u.user.id)
87 }
88 }
89
90 func mapView(_ mapView: MKMapView, rendererFor overlay: any MKOverlay) -> MKOverlayRenderer {
91 if let circle = overlay as? MKCircle {
92 let r = MKCircleRenderer(circle: circle)
93 if circle.title == "selected" {
94 r.fillColor = UIColor.systemBlue.withAlphaComponent(0.18)
95 r.strokeColor = UIColor.systemBlue
96 } else {
97 r.fillColor = UIColor.systemTeal.withAlphaComponent(0.18)
98 r.strokeColor = UIColor.systemTeal
99 }
100 r.lineWidth = 2
101 return r
102 }
103 return MKOverlayRenderer(overlay: overlay)
104 }
105
106 func mapView(_ mapView: MKMapView, regionDidChangeAnimated animated: Bool) {
107 let c = mapView.centerCoordinate
108 parent.onCenterChanged(Coord(lat: c.latitude, lon: c.longitude))
109 }
110
111 @objc func handleTap(_ recognizer: UITapGestureRecognizer) {
112 guard let map = recognizer.view as? MKMapView else { return }
113 // If user tapped on an annotation, MapKit handles it via didSelect. We only get here for empty taps.
114 let point = recognizer.location(in: map)
115 for ann in map.annotations {
116 if let view = map.view(for: ann), view.frame.contains(point) { return }
117 }
118 parent.onMapTap()
119 }
120
121 func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith other: UIGestureRecognizer) -> Bool {
122 true
123 }
124 }
125}
126
127// MARK: - Annotations
128
129final class UserAnnotation: NSObject, MKAnnotation {
130 let user: User
131 let coordinate: CLLocationCoordinate2D
132 init(user: User, coord: Coord) {
133 self.user = user
134 self.coordinate = coord.clLocationCoordinate
135 }
136}
137
138final class WaypointAnnotation: NSObject, MKAnnotation {
139 let waypoint: Waypoint
140 let coordinate: CLLocationCoordinate2D
141 var title: String? { waypoint.name }
142 init(waypoint: Waypoint) {
143 self.waypoint = waypoint
144 self.coordinate = waypoint.coord.clLocationCoordinate
145 }
146}
147
148final class UserAnnotationView: MKAnnotationView {
149 private let label = UILabel()
150 private let imageBackground = UIView()
151
152 override init(annotation: (any MKAnnotation)?, reuseIdentifier: String?) {
153 super.init(annotation: annotation, reuseIdentifier: reuseIdentifier)
154 frame = CGRect(x: 0, y: 0, width: 44, height: 44)
155 imageBackground.frame = bounds
156 imageBackground.layer.cornerRadius = 22
157 imageBackground.layer.borderWidth = 2
158 imageBackground.layer.borderColor = UIColor.systemBlue.cgColor
159 imageBackground.backgroundColor = .systemTeal
160 imageBackground.clipsToBounds = true
161 label.frame = bounds
162 label.textAlignment = .center
163 label.textColor = .white
164 label.font = .systemFont(ofSize: 18, weight: .bold)
165 addSubview(imageBackground)
166 imageBackground.addSubview(label)
167 }
168 required init?(coder: NSCoder) { fatalError() }
169
170 func configure(with user: User) {
171 label.text = String(user.name.first ?? "?")
172 // (Future: load image from data:image base64.)
173 }
174}
175
176final class WaypointAnnotationView: MKAnnotationView {
177 private let icon = UIImageView(image: UIImage(systemName: "mappin.circle.fill"))
178 override init(annotation: (any MKAnnotation)?, reuseIdentifier: String?) {
179 super.init(annotation: annotation, reuseIdentifier: reuseIdentifier)
180 frame = CGRect(x: 0, y: 0, width: 32, height: 32)
181 icon.frame = bounds
182 icon.tintColor = .systemTeal
183 icon.contentMode = .scaleAspectFit
184 addSubview(icon)
185 canShowCallout = true
186 }
187 required init?(coder: NSCoder) { fatalError() }
188 func configure(with wp: Waypoint) {}
189}