-
Notifications
You must be signed in to change notification settings - Fork 7
/
MapViewController.swift
948 lines (764 loc) · 31.5 KB
/
MapViewController.swift
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
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
//
// MapViewController.swift
import Foundation
import UIKit
import MapKit
import CoreLocation
import Alamofire
import Gloss
import PromiseKit
import CoreGraphics
import RSClipperWrapper
class MapViewController: UIViewController, CLLocationManagerDelegate, InitialisesExtendedNavBar {
@IBAction func graphButtonPressed(_ sender: UIBarButtonItem) {
search.cancelSearches()
self.performSegue(withIdentifier: "showGraphs", sender: fbpins)
}
//propertieas to initialise xnavbar with if vc is navigated to
var extendedNavBarColor = UIColor.flatGray.withAlphaComponent(0.33)
var extendedNavBarMessage = "touch cluster of pin for info"
var extendedNavBarShouldShowDate = true
var extendedNavBarFontSize: CGFloat = 12
var extendedNavBarFontColor = UIColor.flatBlack
var extendedNavBarIsHidden = false
//
let defaults = UserDefaults.standard
var searchResults = [SearchResult]()
let locationManager = CLLocationManager()
var location: CLLocation?
var updatingLocation = false
var located = false
var lastLocationError: Error?
let search = Search()
var searchController:UISearchController!
var localSearchRequest:MKLocalSearchRequest!
var localSearch:MKLocalSearch!
var localSearchResponse:MKLocalSearchResponse!
var error:NSError!
var searchCompleted: Bool = false
let clusteringManager = FBClusteringManager()
var fbpins = [SearchResult]()
var monthYear: MonthYear? = nil
var readyToSearch = false
var loader: Loader?
var force: String?
var neighbourhood : String?
var neighbourhoodSquare: [CLLocationCoordinate2D]?
var renderer: MKPolygonRenderer?
var sessionManager : SessionManager?
lazy var slideInTransitioningDelegate = SlideInPresentationManager()
var mapScale: Double?
var searchedArea: [CLLocationCoordinate2D]?
var searchCoords = [CLLocationCoordinate2D]()
@IBAction func adjustSettings(_ sender: UIBarButtonItem) {
search.cancelSearches()
performSegue(withIdentifier: "settings", sender: nil)
}
@IBOutlet weak var toolbar: UIToolbar!
@IBAction func searchMap(_ sender: UIBarButtonItem) {
searchController = UISearchController(searchResultsController: nil)
searchController.hidesNavigationBarDuringPresentation = false
// this is to make cursor not white!
let textFieldInsideSearchBar = searchController.searchBar.value(forKey: "searchField") as? UITextField
textFieldInsideSearchBar?.tintColor = UIColor.lightGray
let textFieldInsideSearchBarLabel = textFieldInsideSearchBar!.value(forKey: "placeholderLabel") as? UILabel
textFieldInsideSearchBarLabel?.text = "Search for UK address..."
self.searchController.searchBar.delegate = self
present(searchController, animated: true, completion: nil)
}
// go to my location
@IBAction func getMyLocation(_ sender: UIBarButtonItem) {
search.cancelSearches()
getLocation()
}
func getLocation() {
defaults.set(nil, forKey: "neighbourhood")
neighbourhood = nil
neighbourhoodSquare = nil
renderer = nil
self.updateDateExtendedNavBarInfo() // authorise
let authStatus = CLLocationManager.authorizationStatus()
if authStatus == .notDetermined {
locationManager.requestWhenInUseAuthorization()
return
}
if authStatus == .denied || authStatus == .restricted {
showLocationServicesDeniedAlert()
return
}
startLocationManager()
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
//put loader back in middle
loader?.center = view.center
findAndDisplayDataPointsInVisibleRegion()
}
func getMKMapRectFromCoords ( ne: CLLocationCoordinate2D, sw: CLLocationCoordinate2D) -> MKMapRect {
let nemp = MKMapPointForCoordinate(ne)
let swmp = MKMapPointForCoordinate(sw)
return MKMapRectMake(min(nemp.x, swmp.x), min(nemp.y, swmp.y), abs(nemp.x-swmp.x), abs(nemp.y-swmp.y))
}
func doesPolyAContainPolyB (a: [CLLocationCoordinate2D], b: [CLLocationCoordinate2D]) -> Bool {
// just check if all points of PolygonB are inside A (should work for convex poly)
let CGpolyA = convertCLPolyToCGPoints(poly: a)
let CGpolyB = convertCLPolyToCGPoints(poly: b)
for point in CGpolyB {
if !Clipper.polygonContainsPoint(CGpolyA, point: point) {
return false
}
}
return true
}
func intersectionOfPolyAndRect (poly: [CLLocationCoordinate2D], rect: MKMapRect) -> [CGPoint] {
let rectAsMapPoints = getCoordsFromRect(rect: rect)
let rectAsCGPoints = convertMKMapPointsToCGPoints(rectAsMapPoints)
let polyAsCGPoints = poly.map {self.mapView.convert($0, toPointTo: self.view) }
let intersection = Clipper.intersectPolygons([polyAsCGPoints], withPolygons: [rectAsCGPoints])
if !intersection.isEmpty {
return intersection[0]
} else {
return []
}
}
func convertCLPolyToCGPoints ( poly: [CLLocationCoordinate2D] ) -> [CGPoint] {
return poly.map {self.mapView.convert($0, toPointTo: self.view) }
}
func getCoordsFromRect (rect: MKMapRect) -> [MKMapPoint] {
let left = MKMapRectGetMinX(rect)
let bottom = MKMapRectGetMinY(rect)
let right = MKMapRectGetMaxX(rect)
let top = MKMapRectGetMaxY(rect)
let bottomLeft = MKMapPoint(x: left, y: bottom)
let topLeft = MKMapPoint(x: left, y: top)
let topRight = MKMapPoint(x: right, y: top)
let bottomRight = MKMapPoint(x: right, y: bottom)
let coords = [bottomLeft, topLeft, topRight, bottomRight]
return coords
}
func convertMKMapPointsToCGPoints( _ mapPoints : [MKMapPoint]) -> [CGPoint] {
let coordsAsCL2d : [CLLocationCoordinate2D] = mapPoints.map { MKCoordinateForMapPoint($0) }
return coordsAsCL2d.map {self.mapView.convert($0, toPointTo: self.view)}
}
func getPolygonOfRectXMinusPoly( fullRect: MKMapRect, excludeArea: [CLLocationCoordinate2D]) -> [[CGPoint]] {
// get both rect coords as CGPoints
let fullRectCoords = convertMKMapPointsToCGPoints(getCoordsFromRect(rect: fullRect))
let excludeAreaCoords = convertCLPolyToCGPoints(poly: excludeArea)
//get polygon of difference
let searchPoly = Clipper.differencePolygons([fullRectCoords], fromPolygons: [excludeAreaCoords])
return searchPoly
}
func convertCGPointsPolyToCL2D(_ poly: [CGPoint]) -> [CLLocationCoordinate2D] {
let polyAsCLL2d : [CLLocationCoordinate2D] = poly.map{self.mapView.convert($0, toCoordinateFrom: self.view)}
return polyAsCLL2d
}
func getUnionOfPolyAndPoly (poly1: [CLLocationCoordinate2D], poly2: [CLLocationCoordinate2D]) -> [CLLocationCoordinate2D] {
let poly1AsCGPoints = convertCLPolyToCGPoints (poly: poly1)
let poly2AsCGPoints = convertCLPolyToCGPoints (poly: poly2)
let union = Clipper.unionPolygons([poly1AsCGPoints], withPolygons: [poly2AsCGPoints])[0]
return convertCGPointsPolyToCL2D(union)
}
func setSearchCoords() -> Bool{
let region = mapView.region
let centre = region.center
let span = region.span
let ne = CLLocationCoordinate2DMake(centre.latitude + span.latitudeDelta / 2.0, centre.longitude - span.longitudeDelta / 2.0)
let sw = CLLocationCoordinate2DMake(centre.latitude - span.latitudeDelta / 2.0, centre.longitude + span.longitudeDelta / 2.0)
let mapRectOfCurrentSearch = getMKMapRectFromCoords(ne: ne, sw: sw)
if let ns = neighbourhoodSquare {
searchCoords = ns
return true
} else {
//get new search region, but don't search all again unless categories changes
if let lastSearchPoly = searchedArea {
//we need currentmap rect as array of CLLocationCoordinate2d points
let mapRectAsPoly = getCoordsFromRect(rect: mapRectOfCurrentSearch)
let mapRectAsCLLCoordinatePoly : [CLLocationCoordinate2D] = mapRectAsPoly.map { MKCoordinateForMapPoint($0) }
// did any searchcriteria change? if so start a new search
let updated = defaults.bool(forKey: "searchUpdated")
if (updated) {
print ("SEARCHCOORD:new search because cat updated")
fbpins = []
searchedArea = nil
searchCoords = mapRectAsCLLCoordinatePoly
return true
}
// check if last search contains mapRectofCurrentSearch
// it will if we zoomed in
if doesPolyAContainPolyB ( a: lastSearchPoly, b: mapRectAsCLLCoordinatePoly) {
// if lastSearchPolygon contains current search rect
print ("SEARCHCOORD:current search contained inside last search - ie zoomed in")
//if search criteria didn;t change, don't do a new search, just send exisiting pins to clustering manager
self.generateFBAnnotations(results: [])
return false
} else if doesPolyAContainPolyB( a: mapRectAsCLLCoordinatePoly, b: lastSearchPoly) {
// if we zoomed out so last search area is contained within mapRect
// start search from scratch as poygon has a hole in the middle
print ("SEARCHCOORD:current rect contains poly- ie zoomed out")
fbpins = []
searchCoords = getCoordsFromRect(rect: mapRectOfCurrentSearch).map { MKCoordinateForMapPoint($0)}
return true
} else {
let intersection = intersectionOfPolyAndRect(poly: lastSearchPoly, rect: mapRectOfCurrentSearch)
if !intersection.isEmpty {
print ("SEARCHCOORD:they intersect")
// if they intersect
let searchPoly = getPolygonOfRectXMinusPoly(fullRect: mapRectOfCurrentSearch, excludeArea: lastSearchPoly)[0]
// convert searchpoly to CLLocations
let searchPolyAsCL2DCoords = convertCGPointsPolyToCL2D(searchPoly)
searchCoords = searchPolyAsCL2DCoords
return true
} else {
print ("SEARCHCOORD:they dont intersect")
// they don't intersect
fbpins = []
searchedArea = nil
searchCoords = getCoordsFromRect(rect: mapRectOfCurrentSearch).map { MKCoordinateForMapPoint($0)}
return true
}
}
} else {
print ("SEARCHCOORD:no previous search")
// no previous search
searchCoords = getCoordsFromRect(rect: mapRectOfCurrentSearch).map { MKCoordinateForMapPoint($0) }
return true
}
}
}
//////////////////////////////////////////////////
// find and display datapoints within viewable region
func findAndDisplayDataPointsInVisibleRegion() {
guard readyToSearch else {
return
}
// if setSearchCoords returns false, we don't carry on search as this area has been searched already
guard setSearchCoords() else {
return
}
search.performSearch(coords: searchCoords ) { results in
if let _ = self.neighbourhoodSquare, let ren = self.renderer {
//renderer not nil if neighbourhood is set
//cull any results that are not within my polygon
let resultsWithinPolygon = results.filter {
let currentMapPoint = MKMapPointForCoordinate($0.coordinate)
let polygonViewPoint: CGPoint = ren.point(for: currentMapPoint)
if (ren.path).contains(polygonViewPoint) {
return true
}
return false }
self.searchedArea = nil
self.generateFBAnnotations(results: resultsWithinPolygon)
} else {
print ("I'm here because renderer is nil")
if let wasSearched = self.searchedArea {
self.searchedArea = self.getUnionOfPolyAndPoly(poly1: wasSearched, poly2: self.searchCoords)
} else {
self.searchedArea = self.searchCoords
}
self.generateFBAnnotations(results: results)
}
// self.searchComplete()
}
}
///////
func getSearchNeighbourhoodID() {
if let n = defaults.object(forKey: "neighbourhood"), let f = defaults.object(forKey: "force") {
if let nUnwrapped = n as? String, let fUnwrapped = f as? String {
neighbourhood = nUnwrapped
force = fUnwrapped
} else {
neighbourhood = nil
force = nil
renderer = nil
neighbourhoodSquare = nil
removeOverlays()
}
}
}
func removeOverlays() {
for overlay in self.mapView!.overlays {
self.mapView!.remove(overlay)
}
}
func removeAnnotations() {
print("removing annotations")
fbpins = []
clusteringManager.removeAll()
clusteringManager.display(annotations: [], onMapView: self.mapView)
}
func getScale () ->Double {
let mapBoundsWidth = Double(self.mapView.bounds.size.width)
let mapRectWidth = self.mapView.visibleMapRect.size.width
let scale = mapBoundsWidth / mapRectWidth
return scale
}
func generateFBAnnotations(results: [SearchResult]) {
fbpins += results
clusteringManager.removeAll()
clusteringManager.add(annotations: fbpins)
DispatchQueue.global(qos: .userInitiated).async {
// let mapBoundsWidth = Double(self.mapView.bounds.size.width)
// let mapRectWidth = self.mapView.visibleMapRect.size.width
let scale = self.getScale()
print ("scale",scale)
let annotationArray = self.clusteringManager.clusteredAnnotations(withinMapRect: self.mapView.visibleMapRect, zoomScale: scale)
print ("annotatoins array \(annotationArray)")
DispatchQueue.main.async {
self.clusteringManager.display(annotations: annotationArray, onMapView:self.mapView)
}
}
}
func getNeighbourhoodBoundary(force: String, neighbourhood: String) -> Promise<[CLLocationCoordinate2D]> {
self.removeOverlays()
let config : URLSessionConfiguration = {
let configuration = URLSessionConfiguration.default
configuration.requestCachePolicy = .returnCacheDataElseLoad
return configuration
}()
sessionManager = Alamofire.SessionManager(configuration: config)
let searchURLString = "https://data.police.uk/api/\(force)/\(neighbourhood)/boundary"
let searchURLStringEncoded = searchURLString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
let searchURL = URL (string: searchURLStringEncoded!)
return Promise { fulfill, reject in
if (self.loader == nil) {
self.loader = Loader(message: "loading region...", size: "small")
self.loader?.center = view.center
self.view.addSubview(self.loader!)
}
sessionManager!.request(searchURL!)
.validate()
.responseJSON() { response in
switch response.result {
case .success(let dict):
guard let dictArray = dict as? [NSDictionary] else {
return
}
var coordResults: [NCoords] = []
for result in dictArray {
if let r = NCoords(json: result as! JSON){
coordResults.append(r)
}
}
let coordResAsCLCoords: [CLLocationCoordinate2D] = coordResults.map{CLLocationCoordinate2DMake($0.latitude,$0.longitude)}
// lets try and get the map region for this neighbourhood
var r : MKMapRect = MKMapRectNull
for coord in coordResAsCLCoords {
let p: MKMapPoint = MKMapPointForCoordinate(coord)
r = MKMapRectUnion(r, MKMapRectMake(p.x, p.y, 0, 0))
}
// draw polygon on map
let polygon = MKPolygon(coordinates: coordResAsCLCoords, count: coordResAsCLCoords.count)
self.mapView?.add(polygon)
let lowerLeft = MKCoordinateForMapPoint(MKMapPoint(x: r.origin.x, y: r.origin.y))
let lowerRight = MKCoordinateForMapPoint(MKMapPoint(x: r.origin.x + r.size.width, y: r.origin.y))
let topLeft = MKCoordinateForMapPoint(MKMapPoint(x: r.origin.x, y: r.origin.y + r.size.height))
let topRight = MKCoordinateForMapPoint(MKMapPoint(x: r.origin.x + r.size.width, y: r.origin.y + r.size.height))
self.neighbourhoodSquare = [lowerLeft,lowerRight,topRight,topLeft]
let region = MKCoordinateRegionForMapRect(r)
self.mapView.setRegion(region, animated: false)
self.loader?.removeFromSuperview()
self.loader = nil
fulfill(coordResAsCLCoords)
case .failure (let err):
self.loader?.removeFromSuperview()
self.loader = nil
reject(err)
}
}
}
}
func getDateLastUpdated( _ setStart: Bool = false) -> Promise<String> {
return Promise { fulfill, reject in
Alamofire.request("https://data.police.uk/api/crime-last-updated")
.validate()
.responseJSON() { response in
switch response.result {
case .success(let dict):
guard let dictionary = dict as? [String:Any], let date = dictionary["date"] as? String else {
return
}
let formattedDate = MonthYear(date: date)
self.defaults.set(formattedDate.month, forKey: "monthLastUpdated")
self.defaults.set(formattedDate.year, forKey: "yearLastUpdated")
if (setStart) {
self.defaults.set(formattedDate.month, forKey: "startMonth")
self.defaults.set(formattedDate.year, forKey: "startYear")
}
self.updateDateExtendedNavBarInfo()
fulfill(date)
case .failure(let err):
reject(err)
}
}
}
}
///////////////
func updateDateExtendedNavBarInfo() {
let nav = self.navigationController as! ExtendedNavController
nav.updateInfo()
}
@IBOutlet weak var mapView: MKMapView!
override func viewDidLoad() {
super.viewDidLoad()
navigationController?.delegate = self
search.delegate = self
if defaults.object(forKey: "startMonth") == nil {
let _ = getDateLastUpdated(true).then { _ -> Void in
self.updateDateExtendedNavBarInfo()
}
}
//appearance
let barTintColor = UIColor.flatMintDark
toolbar.barTintColor=barTintColor
//gesture recogniser to hide clusters/pins when zooming
let zoom = UIPinchGestureRecognizer ( target: self, action: #selector(self.handleZoom(_:)))
zoom.delegate = self
mapView.addGestureRecognizer(zoom)
mapView.isUserInteractionEnabled = true
startUp()
if neighbourhood == nil {
//load users location on first load if no neighbourhood set, but not when going back to mapmevery time
getLocation()
}
}
func startUp() {
//initiation routine
// set values of neighbour and force from userDefaults
getSearchNeighbourhoodID()
if let n = neighbourhood, let f = force {
let getDate = getDateLastUpdated()
let getNeighbourhood = getNeighbourhoodBoundary(force: f, neighbourhood: n)
when (fulfilled: getDate, getNeighbourhood).then {
date, coords -> Void in
self.readyToSearch = true
self.findAndDisplayDataPointsInVisibleRegion()
}.catch { error in
print ("error", error )
}
} else {
getDateLastUpdated().then {
theDate ->Void in
self.readyToSearch = true
self.getLocation()
}.catch {
error in
print (error)
}
}
}
override func viewWillAppear(_ animated: Bool) {
updateDateExtendedNavBarInfo()
// check if cats, dates or neighbourhood changed, only do new search if they have
let updated = defaults.bool(forKey: "searchUpdated")
print (updated)
if (updated) {
getSearchNeighbourhoodID()
if let n = neighbourhood, let f = force {
let _ = getNeighbourhoodBoundary(force: f, neighbourhood: n).then {_ in
self.findAndDisplayDataPointsInVisibleRegion()
}
} else {
findAndDisplayDataPointsInVisibleRegion()
}
}
}
func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
if overlay is MKPolygon {
renderer = MKPolygonRenderer(overlay: overlay)
renderer?.strokeColor = .flatOrange
renderer?.lineWidth = 2
return renderer!
}
return MKOverlayRenderer()
}
func handleZoom( _ sender: UIPinchGestureRecognizer) {
if (sender.state == UIGestureRecognizerState.began) {
mapScale = getScale()
}
if (sender.state == UIGestureRecognizerState.ended) {
if let startScale = mapScale {
if getScale() < startScale {
//zoomed out
if neighbourhood == nil {
findAndDisplayDataPointsInVisibleRegion()
}
}
mapScale = nil
}
generateFBAnnotations(results: [])
}
}
}
extension MapViewController: MKMapViewDelegate {
func mapView(_ mapView: MKMapView, regionDidChangeAnimated animated: Bool) {
if neighbourhood == nil {
if let startScale = self.mapScale {
if getScale() < startScale {
//zoomed out
findAndDisplayDataPointsInVisibleRegion()
}
} else {
// didn't zoom so search
findAndDisplayDataPointsInVisibleRegion()
}
}
}
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
if annotation is MKUserLocation {
return nil
}
var reuseId = ""
if annotation is FBAnnotationCluster {
reuseId = "Cluster"
var clusterView = mapView.dequeueReusableAnnotationView(withIdentifier: reuseId)
if clusterView == nil {
clusterView = FBAnnotationClusterView(annotation: annotation, reuseIdentifier: reuseId, configuration: FBAnnotationClusterViewConfiguration.default())
(clusterView as! FBAnnotationClusterView).delegate = self
} else {
clusterView?.annotation = annotation
(clusterView as! FBAnnotationClusterView).reset()
}
return clusterView
} else {
reuseId = "Pin"
var pinView = mapView.dequeueReusableAnnotationView(withIdentifier: reuseId) as? MKPinAnnotationView
if pinView == nil {
pinView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
pinView?.isEnabled = true
pinView?.canShowCallout = true
let rightButton = UIButton(type: .detailDisclosure)
rightButton.tintColor = UIColor.gray
let resultToDisplay = annotation as! SearchResult
let i = fbpins.index(of: resultToDisplay)
if let ind = i {
rightButton.tag = ind
}
rightButton.addTarget(self,action: #selector(showDetails),for: .touchUpInside)
pinView?.rightCalloutAccessoryView = rightButton
pinView?.pinTintColor = resultToDisplay.color ?? UIColor.white
let subtitleView = UILabel()
subtitleView.font = subtitleView.font.withSize(10)
subtitleView.textColor = UIColor.gray
subtitleView.numberOfLines = 0
subtitleView.text = annotation.subtitle!
pinView!.detailCalloutAccessoryView = subtitleView
} else {
let resultToDisplay = annotation as! SearchResult
pinView?.annotation = annotation
pinView?.pinTintColor = resultToDisplay.color
let i = fbpins.index(of: resultToDisplay)
if let ind = i {
pinView?.rightCalloutAccessoryView?.tag = ind
}
}
return pinView
}
}
func showDetails(_ sender: UIButton) {
performSegue(withIdentifier: "showDetail", sender: sender.tag)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
search.cancelSearches()
if segue.identifier == "showGraphs" {
let controller = segue.destination as! GraphParentViewController
controller.data = fbpins
controller.neighbourhood = self.neighbourhood
}
if segue.identifier == "showDetail" {
let controller = segue.destination as! DetailViewController
controller.data = fbpins[sender as! Int]
}
if segue.identifier == "setDate" {
if let controller = segue.destination as? DateController {
controller.mode = sender as! String?
}
}
if segue.identifier == "showClusterInfo" {
let controller = segue.destination as! ClusterInfoTableViewController
controller.cluster = sender as? FBAnnotationCluster
}
if segue.identifier == "settings" {
print ("loading settings")
let controller = segue.destination as! SettingsTableViewController
slideInTransitioningDelegate.direction = .left
// slideInTransitioningDelegate.disableCompactHeight = true
controller.transitioningDelegate = slideInTransitioningDelegate
controller.modalPresentationStyle = .custom
controller.delegate = self
}
if segue.identifier == "loadControls" {
let tabController = segue.destination as! UITabBarController
if let catController = tabController.viewControllers?[0] as? ControlsTableViewController{
catController.checked = sender as! [Bool]?
// catController.enabledSections = self.enabledSections
// catController.delegate = self
}
}
}
func showLocationServicesDeniedAlert() {
let alert = UIAlertController(title: "Location Services Disabled",message:"Please enable location services for this app in Settings.", preferredStyle: .alert)
let okAction = UIAlertAction(title: "OK", style: .default, handler: nil)
alert.addAction(okAction)
present(alert, animated: true, completion: nil)
}
// MARK: - CLLocationManagerDelegate
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print ("fail \(error)")
if (error as NSError).code == CLError.locationUnknown.rawValue {
return
}
lastLocationError = error
print ("alert error")
stopLocationManager()
}
func startLocationManager() {
print ("starting mananger")
if CLLocationManager.locationServicesEnabled() {
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters
locationManager.startUpdatingLocation()
updatingLocation = true
}
}
func stopLocationManager() {
if updatingLocation {
locationManager.stopUpdatingLocation()
locationManager.delegate = nil
updatingLocation = false
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
print ("here")
let newLocation = locations.last!
if newLocation.timestamp.timeIntervalSinceNow < -5 {
print("too old")
return
}
if newLocation.horizontalAccuracy < 0 {
print ("less than 0")
return
}
if location == nil || location!.horizontalAccuracy > newLocation.horizontalAccuracy || located {
located = true
print ("improving")
lastLocationError = nil
location = newLocation
if newLocation.horizontalAccuracy <= locationManager.desiredAccuracy {
search.cancelSearches()
print("*** We're done!")
let center = CLLocationCoordinate2D(latitude: newLocation.coordinate.latitude, longitude: newLocation.coordinate.longitude)
let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))
self.mapView.setRegion(region, animated: true)
stopLocationManager()
}
}
}
}
extension MapViewController: UIGestureRecognizerDelegate {
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
}
extension MapViewController: UISearchBarDelegate {
func searchBarSearchButtonClicked(_ searchBar: UISearchBar){
searchBar.resignFirstResponder()
dismiss(animated: true, completion: nil)
localSearchRequest = MKLocalSearchRequest()
localSearchRequest.naturalLanguageQuery = searchBar.text
localSearch = MKLocalSearch(request: localSearchRequest)
localSearch.start {
(localSearchResponse, error) -> Void in
if localSearchResponse == nil{
let alertController = UIAlertController(title: nil, message: "Place Not Found", preferredStyle: UIAlertControllerStyle.alert)
alertController.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.default, handler: nil))
self.present(alertController, animated: true, completion: nil)
return
}
////
self.defaults.set(nil, forKey: "neighbourhood")
self.neighbourhoodSquare = nil
self.renderer = nil
self.updateDateExtendedNavBarInfo()
self.mapView.setRegion(localSearchResponse!.boundingRegion, animated: true)
}
}
}
extension MapViewController: FBAnnotationClusterViewDelegate {
func touchBegan() {
search.cancelSearches()
}
func showClusterInfo(for cluster: FBAnnotationCluster) {
performSegue(withIdentifier: "showClusterInfo", sender: cluster)
}
}
extension MapViewController: UINavigationControllerDelegate {
func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) {
let nav = navigationController as! ExtendedNavController
if let controller = viewController as? InitialisesExtendedNavBar {
nav.setExtendedBarColor(controller.extendedNavBarColor)
nav.setStatusMessage(message: controller.extendedNavBarMessage, size: controller.extendedNavBarFontSize, color: controller.extendedNavBarFontColor )
nav.showDate(controller.extendedNavBarShouldShowDate)
nav.shouldHideExtendedBar(controller.extendedNavBarIsHidden)
}
if let _ = viewController as? MapViewController {
nav.updateInfo() }
}
}
extension MapViewController: SettingsTableViewControllerDelegate {
func goTo(_ destination: String) {
switch (destination) {
case "startDate":
self.performSegue(withIdentifier: "setDate" , sender: "start")
case "endDate":
self.performSegue(withIdentifier: "setDate" , sender: "end")
default:
self.performSegue(withIdentifier: destination, sender: nil)
}
}
}
extension MapViewController: SearchDelegate {
func searchStarted() {
searchCompleted = false
let nav = navigationController as! ExtendedNavController
if let _ = nav.visibleViewController as? MapViewController {
nav.setStatusMessage(message: "loading...")
}
if (loader == nil) {
loader = Loader(message: "loading crime data...")
loader?.center = view.center
self.view.addSubview(loader!)
}
}
func searchCompleted(_ success: Bool) {
if (!success) {
showSomeFailedAlert()
} else {
searchCompleted = true
defaults.set(false,forKey:"searchUpdated")
self.loader?.removeFromSuperview()
self.loader = nil
let nav = self.navigationController as! ExtendedNavController
if let _ = nav.visibleViewController as? MapViewController {
nav.setStatusMessage(message: "touch pin or cluster for info")
}
}
}
func showSomeFailedAlert() {
let alert = UIAlertController(title: "Data failed for some categories",message:"Try using a smaller search area.", preferredStyle: .alert)
let okAction = UIAlertAction(title: "OK", style: .default, handler: nil)
alert.addAction(okAction)
present(alert, animated: true, completion: {self.clearStatusMessage()})
}
func clearStatusMessage() {
if let nav = navigationController as? ExtendedNavController {
nav.setStatusMessage(message: "")
}
}
func searchStatus(cat: String, success: Bool){
if (success) {
self.loader?.messageLabel.text = "\(cat) loaded"
// nav.setStatusMessage(message: "\(cat) loaded", color: .black)
} else {
self.loader?.messageLabel.text = "\(cat) failed"
}
}
}