Reportage/Views/Charts/PlacesMap.swift (3929B)
1import MapKit
2import SwiftUI
3
4
5
6struct PlacesMap: View {
7 let places: [MapPlace]
8 var interactive = true
9 var selection: Binding<String?>?
10
11 @State private var position = MapCameraPosition.automatic
12
13 var body: some View {
14 let most = places.map(\.count).max() ?? 1
15 Map(
16 position: $position,
17 interactionModes: interactive ? [.pan, .zoom] : [],
18 selection: selection ?? .constant(nil)
19 ) {
20
21 ForEach(places) { place in
22 Annotation(place.name, coordinate: place.centre, anchor: .center) {
23 PlaceMark(
24 diameter: Self.diameter(of: place, most: most),
25 isSelected: selection?.wrappedValue == place.id)
26 }
27 .annotationTitles(.hidden)
28 .tag(place.id)
29 }
30 }
31 .mapStyle(.standard(emphasis: .muted, pointsOfInterest: .excludingAll))
32 .onChange(of: places.map(\.id)) { position = .automatic }
33 }
34
35
36
37 static func diameter(of place: MapPlace, most: Int) -> CGFloat {
38 10 + 26 * sqrt(CGFloat(place.count) / CGFloat(max(most, 1)))
39 }
40}
41
42
43private struct PlaceMark: View {
44 let diameter: CGFloat
45 let isSelected: Bool
46
47 var body: some View {
48 Circle()
49 .fill(Theme.accent.opacity(isSelected ? 1 : 0.75))
50 .frame(width: diameter, height: diameter)
51 .overlay(Circle().strokeBorder(isSelected ? Theme.ink : Theme.paper, lineWidth: 2))
52 }
53}
54
55
56struct PlacesMapView: View {
57 let model: ChartsModel
58 @State private var selection: String?
59
60 var body: some View {
61 let summary = model.data.context.places
62 VStack(spacing: 0) {
63 PlacesMap(places: summary?.places ?? [], selection: $selection)
64 VStack(alignment: .leading, spacing: Theme.lineGap) {
65 if let place = summary?.places.first(where: { $0.id == selection }) {
66 Text(place.name)
67 .font(Theme.serif(.title3, weight: .medium))
68 Text("^[\(place.count) report](inflect: true)")
69 .font(.footnote)
70 .foregroundStyle(Theme.muted)
71 } else {
72 Text(model.data.period.title)
73 .font(Theme.serif(.title3, weight: .medium))
74 footnote(for: summary)
75 .font(.footnote)
76 .foregroundStyle(Theme.muted)
77 }
78 }
79 .frame(maxWidth: .infinity, alignment: .leading)
80 .padding(.horizontal, Theme.margin)
81 .padding(.vertical, Theme.itemGap)
82 .background(Theme.paper)
83 .overlay(alignment: .top) { Rectangle().fill(Theme.rule).frame(height: 1) }
84 }
85 .foregroundStyle(Theme.ink)
86 .navigationTitle("Places")
87 .navigationBarTitleDisplayMode(.inline)
88 }
89
90 private func footnote(for summary: PlacesSummary?) -> Text {
91 let shown = Text("^[\(summary?.places.count ?? 0) place](inflect: true). Tap one to see it.")
92 guard let unplaced = summary?.unplaced, unplaced > 0 else { return shown }
93 return Text("\(shown) ^[\(unplaced) place](inflect: true) without a location can't be shown.")
94 }
95}
96
97extension MapPlace {
98 fileprivate var centre: CLLocationCoordinate2D {
99 CLLocationCoordinate2D(latitude: coordinate.latitude, longitude: coordinate.longitude)
100 }
101}