Created
October 23, 2024 13:37
-
-
Save takoikatakotako/628f4c2c184d72001847adf47e173f2e to your computer and use it in GitHub Desktop.
SwiftUIでMapを表示し、自分の位置を中心にする
This file contains hidden or 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 ContentView: View { | |
| @StateObject var viewState: ContentViewState = ContentViewState() | |
| var body: some View { | |
| ZStack { | |
| if let location = viewState.location { | |
| Map( | |
| initialPosition: | |
| MapCameraPosition.region( | |
| MKCoordinateRegion( | |
| center: location, | |
| latitudinalMeters: 300, | |
| longitudinalMeters: 300 | |
| ) | |
| ) | |
| ) | |
| } else { | |
| Text("Loading...") | |
| } | |
| } | |
| .onAppear { | |
| viewState.onAppear() | |
| } | |
| } | |
| } | |
| #Preview { | |
| ContentView(viewState: ContentViewState()) | |
| } |
This file contains hidden or 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 Foundation | |
| import CoreLocation | |
| class ContentViewState: NSObject, ObservableObject { | |
| @Published var location: CLLocationCoordinate2D? | |
| private let locationManager = CLLocationManager() | |
| func onAppear() { | |
| locationManager.delegate = self | |
| locationManager.requestWhenInUseAuthorization() | |
| let status = locationManager.authorizationStatus | |
| switch status { | |
| case .authorizedWhenInUse: | |
| locationManager.startUpdatingLocation() | |
| default: | |
| break | |
| } | |
| } | |
| } | |
| extension ContentViewState: CLLocationManagerDelegate { | |
| func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) { | |
| switch status { | |
| case .authorizedWhenInUse: | |
| locationManager.startUpdatingLocation() | |
| default: | |
| break | |
| } | |
| } | |
| func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { | |
| self.location = manager.location?.coordinate | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment