Created
October 23, 2024 13:33
-
-
Save takoikatakotako/35bb7a8e902c27e0fe6317609b59a062 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 | |
| ) | |
| ) | |
| ) { | |
| MapCircle(center: location, radius: CLLocationDistance(10)) | |
| .foregroundStyle(Color.red.opacity(0.6)) | |
| .mapOverlayLevel(level: .aboveRoads) | |
| } | |
| .mapControls { | |
| MapCompass() | |
| } | |
| } else { | |
| Text("Loading...") | |
| } | |
| } | |
| .onAppear { | |
| viewState.onAppear() | |
| } | |
| } | |
| } |
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