-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMapView.swift
More file actions
256 lines (231 loc) · 10.5 KB
/
MapView.swift
File metadata and controls
256 lines (231 loc) · 10.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
import SwiftUI
import MapKit
struct TappableMapView: UIViewRepresentable {
let onTap: ((CLLocationCoordinate2D) -> Void)?
@Binding var annotations: [MKPointAnnotation]
@Binding var region: MKCoordinateRegion
@Binding var shouldCenter: Bool
func makeUIView(context: Context) -> MKMapView {
let mapView = MKMapView(frame: .zero)
mapView.delegate = context.coordinator
// 1) Allowed region
// Currently: ±5 km around Memorial Union
let center = CLLocationCoordinate2D(latitude: 38.54237287621318,
longitude: -121.74955185519764)
let allowedRegion = MKCoordinateRegion(center: center,
latitudinalMeters: 10_000,
longitudinalMeters: 10_000)
// Pan boundary:
let boundary = MKMapView.CameraBoundary(coordinateRegion: allowedRegion)
mapView.setCameraBoundary(boundary, animated: false)
// Zoom Limit:
let zoomRange = MKMapView.CameraZoomRange(minCenterCoordinateDistance: 200,maxCenterCoordinateDistance: 5_000)
mapView.setCameraZoomRange(zoomRange, animated: false)
// Initial region
let tapGesture = UITapGestureRecognizer(
target: context.coordinator,
action: #selector(Coordinator.handleTap(_:))
)
tapGesture.delegate = context.coordinator
mapView.addGestureRecognizer(tapGesture)
mapView.setRegion(allowedRegion, animated: false)
return mapView
}
func updateUIView(_ uiView: MKMapView, context: Context) {
if shouldCenter {
uiView.setRegion(region, animated: true)
DispatchQueue.main.async {
self.shouldCenter = false
}
}
uiView.removeAnnotations(uiView.annotations)
uiView.addAnnotations(annotations)
}
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
class Coordinator: NSObject, MKMapViewDelegate, UIGestureRecognizerDelegate {
var parent: TappableMapView
init(_ parent: TappableMapView) {
self.parent = parent
}
@objc func handleTap(_ gestureRecognizer: UITapGestureRecognizer) {
guard let mapView = gestureRecognizer.view as? MKMapView else { return }
// Close annotation when user clicks else where
if !mapView.selectedAnnotations.isEmpty {
mapView.selectedAnnotations.forEach {
mapView.deselectAnnotation($0, animated: true)
}
return
}
// When user click on map check if an annotation is opened
// If not opened then prompt create a new pin
let tapPoint = gestureRecognizer.location(in: mapView)
let coordinate = mapView.convert(tapPoint, toCoordinateFrom: mapView)
parent.onTap?(coordinate)
}
func mapView(_ mapView: MKMapView, regionDidChangeAnimated animated: Bool) {
parent.region = mapView.region
}
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
// don’t override the blue “user location” dot
guard !(annotation is MKUserLocation) else { return nil }
let reuseID = "marker"
var markerView = mapView.dequeueReusableAnnotationView(withIdentifier: reuseID)
as? MKMarkerAnnotationView
if markerView == nil {
markerView = MKMarkerAnnotationView(annotation: annotation, reuseIdentifier: reuseID)
markerView!.canShowCallout = true
markerView!.animatesWhenAdded = true
// "i" button when user click on the pin
markerView!.rightCalloutAccessoryView = UIButton(type: .detailDisclosure)
}
else {
markerView!.annotation = annotation
}
return markerView
}
// Respond to taps on the callout accessory
func mapView(_ mapView: MKMapView,
annotationView view: MKAnnotationView,
calloutAccessoryControlTapped control: UIControl) {
guard view.annotation is MKPointAnnotation else { return }
// here we ha ve the option to pass pin.title or pin.subtitle back into SwiftUI:
// parent.onCalloutTap?(pin)
}
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer,
shouldReceive touch: UITouch) -> Bool {
guard let mapView = gestureRecognizer.view as? MKMapView else { return true }
let pt = touch.location(in: mapView)
// if the user tapped on an annotationView, do not allow the user to set a new pin when tapping else where on the map
if mapView.hitTest(pt, with: nil) is MKAnnotationView {
return false
}
return true
}
}
}
struct MapView: View {
@Binding var region: MKCoordinateRegion
let pins: [MKPointAnnotation]
let onTap: (CLLocationCoordinate2D) -> Void
@State private var annotations: [MKPointAnnotation] = []
@State private var shouldCenter: Bool = false
// @State private var shouldCenterMU: Bool = false
@State private var tappedCoordinate: CLLocationCoordinate2D? = nil
@State private var newMarkerName: String = ""
@State private var showMarkerEditor: Bool = false
// @State private var annotationsMU: [MKPointAnnotation] = {
// let memorialAnnotation = MKPointAnnotation()
// memorialAnnotation.coordinate = CLLocationCoordinate2D(latitude: 38.54237287621318,longitude: -121.74955185519764)
// memorialAnnotation.title = "Memorial Union"
// return [memorialAnnotation]
// }()
// @State private var regionMU = MKCoordinateRegion(
// center: CLLocationCoordinate2D(latitude: 38.54237287621318,longitude: -121.74955185519764),
// latitudinalMeters: 5000,
// longitudinalMeters: 5000
// )
var body: some View {
ZStack {
// TappableMapView(
// onTap: { coordinate in
// tappedCoordinate = coordinate
// newMarkerName = ""
// showMarkerEditor = true
// },
// annotations: $annotationsMU,
// region: $regionMU,
// shouldCenter: $shouldCenterMU)
// .edgesIgnoringSafeArea(.all)
TappableMapView(
onTap: onTap,
annotations: $annotations,
region: $region,
shouldCenter: $shouldCenter
).edgesIgnoringSafeArea(.all)
VStack {
Spacer()
HStack {
Spacer()
Button {
region = MKCoordinateRegion(
center: CLLocationCoordinate2D(latitude: 38.54237287621318,
longitude: -121.74955185519764),
latitudinalMeters: 200,
longitudinalMeters: 200
)
shouldCenter = true
} label: {
Text("MU")
.font(.headline)
.foregroundColor(.white)
.frame(width: 50, height: 50)
}.background(
Circle()
.fill(Color.blue.opacity(0.85))
.shadow(radius: 4)
)
.padding(.trailing, 20)
.padding(.bottom, 30)
}
}
if showMarkerEditor {
Color.black.opacity(0.4)
.edgesIgnoringSafeArea(.all)
VStack(spacing: 20) {
Text("Enter a name for the location:")
.font(.headline)
TextField("Location name", text: $newMarkerName)
.textFieldStyle(RoundedBorderTextFieldStyle())
.padding(.horizontal)
HStack {
Button(action: {
showMarkerEditor = false
}, label: {
Text("Cancel")
.frame(maxWidth: .infinity)
.padding()
.background(Color.gray.opacity(0.2))
.cornerRadius(8)
})
Button(action: {
if let coordinate = tappedCoordinate,
!newMarkerName.trimmingCharacters(in: .whitespaces).isEmpty {
let newAnnotation = MKPointAnnotation()
newAnnotation.coordinate = coordinate
newAnnotation.title = newMarkerName
newAnnotation.subtitle = "Brief description goes here"
annotations.append(newAnnotation)
}
showMarkerEditor = false
}, label: {
Text("Add")
.frame(maxWidth: .infinity)
.padding()
.background(Color.blue.opacity(0.7))
.foregroundColor(.white)
.cornerRadius(8)
})
}
.padding(.horizontal)
}
.padding()
.background(Color.white)
.cornerRadius(12)
.padding(40)
}
}
.onAppear{
annotations = pins
}
.onChange(of: pins) { newPins in
annotations = newPins
}
}
}
//struct ContentView_Previews: PreviewProvider {
// static var previews: some View {
// MapView()
// }
//}