From 0c9997993d570d8deb79ea6c0f22ae4fdb0b538d Mon Sep 17 00:00:00 2001 From: Milan Stute Date: Thu, 11 Mar 2021 08:18:11 +0100 Subject: [PATCH] Map fits all accessories by default --- .../OpenHaystack/MapViewController.swift | 32 ++++++++++++------- 1 file changed, 20 insertions(+), 12 deletions(-) diff --git a/OpenHaystack/OpenHaystack/MapViewController.swift b/OpenHaystack/OpenHaystack/MapViewController.swift index 193e5a2..b6568dc 100755 --- a/OpenHaystack/OpenHaystack/MapViewController.swift +++ b/OpenHaystack/OpenHaystack/MapViewController.swift @@ -21,12 +21,7 @@ final class MapViewController: NSViewController, MKMapViewDelegate { func zoom(on accessory: Accessory?) { self.focusedAccessory = accessory - guard let location = accessory?.lastLocation else { return } - let span = MKCoordinateSpan(latitudeDelta: 0.005, longitudeDelta: 0.005) - let region = MKCoordinateRegion(center: location.coordinate, span: span) - DispatchQueue.main.async { - self.mapView.setRegion(region, animated: true) - } + self.zoomInOnSelection() } func addLastLocations(from accessories: [Accessory]) { @@ -37,15 +32,28 @@ final class MapViewController: NSViewController, MKMapViewDelegate { let annotation = AccessoryAnnotation(accessory: accessory) self.mapView.addAnnotation(annotation) } + self.zoomInOnSelection() + } - // Zoom to first location - if focusedAccessory == nil, let location = accessories.first(where: { $0.lastLocation != nil })?.lastLocation { - let span = MKCoordinateSpan(latitudeDelta: 0.005, longitudeDelta: 0.005) - let region = MKCoordinateRegion(center: location.coordinate, span: span) - DispatchQueue.main.async { - self.mapView.setRegion(region, animated: true) + func zoomInOnSelection() { + var annotations = [MKAnnotation]() + + if focusedAccessory == nil { + // Show all locations + annotations = self.mapView.annotations + } else { + // Show focused accessory + let focusedAnnotation: MKAnnotation? = self.mapView.annotations.first(where: { annotation in + let accessoryAnnotation = annotation as! AccessoryAnnotation + return accessoryAnnotation.accessory == self.focusedAccessory + }) + if let annotation = focusedAnnotation { + annotations = [annotation] } } + DispatchQueue.main.async { + self.mapView.showAnnotations(annotations, animated: true) + } } func changeMapType(_ mapType: MKMapType) {