Created
October 23, 2024 13:35
-
-
Save takoikatakotako/6eaa30c5687b16d6b0b33ddd38a4b327 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) | |
| } | |
| } 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