Last active
April 8, 2021 14:49
-
-
Save CrystalKnightCodes/c090ffdbe453852b75d7b6ac257ffce0 to your computer and use it in GitHub Desktop.
TabView Tutorial Search Map View
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import SwiftUI | |
import MapKit | |
struct SearchMapView: View { | |
// MARK: - Properties | |
@ObservedObject private var regionModel = RegionModel( | |
region: MKCoordinateRegion( | |
center: CLLocationCoordinate2D( | |
latitude: 39.8333, | |
longitude: -98.5833 | |
), | |
span: MKCoordinateSpan( | |
latitudeDelta: 35, | |
longitudeDelta: 35 | |
) | |
) | |
) | |
@Binding var results: [Vacation] | |
@Binding var selection: Int | |
// MARK: - View | |
var body: some View { | |
Map( | |
coordinateRegion: $regionModel.region, | |
annotationItems: !results.isEmpty ? results[selection].places : []) { place in | |
MapMarker(coordinate: place.coordinate) | |
} | |
.onAppear { findCenter() } | |
.onChange(of: selection, perform: { _ in | |
findCenter() | |
}) | |
.onChange(of: results, perform: { _ in | |
findCenter() | |
}) | |
.ignoresSafeArea(edges: .horizontal) | |
} | |
// MARK: - Methods | |
func findCenter() { | |
if !results.isEmpty, let place = results[selection].places.first { | |
regionModel.region.center = place.coordinate | |
regionModel.region.span = MKCoordinateSpan( | |
latitudeDelta: 3, | |
longitudeDelta: 3 | |
) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment