From 639a0f49a03910f5033872fa3b9388b1ec50ec51 Mon Sep 17 00:00:00 2001 From: Joshua Pirihi Date: Mon, 27 Dec 2021 08:00:47 +1300 Subject: [PATCH] On initial load, move the map to the region that bounds the mesh --- MeshtasticClient/Views/Map/MapView.swift | 36 ++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/MeshtasticClient/Views/Map/MapView.swift b/MeshtasticClient/Views/Map/MapView.swift index ebdd6742..39967558 100644 --- a/MeshtasticClient/Views/Map/MapView.swift +++ b/MeshtasticClient/Views/Map/MapView.swift @@ -21,6 +21,8 @@ struct MapView: UIViewRepresentable { //observe changes to the key in UserDefaults @AppStorage("meshMapType") var type: String = "hybrid" + //@State var needToMoveToMeshRegion: Bool = true + func makeUIView(context: Context) -> MKMapView { let map = MKMapView(frame: .zero) @@ -31,6 +33,8 @@ struct MapView: UIViewRepresentable { map.setRegion(map.regionThatFits(region), animated: false) //self.updateMapType(map) + self.showNodePositions(to: map) + self.moveToMeshRegion(in: map) map.register(PositionAnnotationView.self, forAnnotationViewWithReuseIdentifier: NSStringFromClass(PositionAnnotationView.self)) @@ -44,6 +48,38 @@ struct MapView: UIViewRepresentable { self.updateMapType(view) self.showNodePositions(to: view) + + //if (self.needToMoveToMeshRegion) { + // self.moveToMeshRegion(in: view) + // self.needToMoveToMeshRegion = false + //} + } + + func moveToMeshRegion(in mapView: MKMapView) { + //go through the annotations and create a bounding box that encloses them + + var minLat: CLLocationDegrees = 90.0 + var maxLat: CLLocationDegrees = -90.0 + var minLon: CLLocationDegrees = 180.0 + var maxLon: CLLocationDegrees = -180.0 + + for annotation in mapView.annotations { + if annotation.isKind(of: PositionAnnotation.self) { + minLat = min(minLat, annotation.coordinate.latitude) + maxLat = max(maxLat, annotation.coordinate.latitude) + minLon = min(minLon, annotation.coordinate.longitude) + maxLon = max(maxLon, annotation.coordinate.longitude) + } + } + let centerCoord = CLLocationCoordinate2D(latitude: (minLat+maxLat)/2, longitude: (minLon+maxLon)/2) + + let span = MKCoordinateSpan(latitudeDelta: (maxLat-minLat)*1.5, longitudeDelta: (maxLon-minLon)*1.5) + + let region = mapView.regionThatFits(MKCoordinateRegion(center: centerCoord, span: span)) + + mapView.setRegion(region, animated: true) + + } func updateMapType(_ map: MKMapView) {