CLLocationManager()を使って位置情報を取得し、マップ上にPinを表示した後、(たとえば)消すボタンでピンを消したいです。
clear_flagのture/falseでstruct MapView内のfunc updateUIView内で消すように考えたのですが、そもそも消すボタンを押してもlocationが更新されないから(?)うまくfunc updateUIViewに飛びません。
そもそも、このような面倒なことをしなくても、なんらかのfunc等を呼べば、マップ内のPin等追加した要素が消せる方法等もあるのでしょうか?
すいません。お知恵を拝借したく、よろしくお願いいたします。
ContentView.swift
1// ContentView.swift 2import SwiftUI 3import MapKit 4var latetude : Double = 0.0 5var longitude : Double = 0.0 6var clear_flag = false 7 8struct ContentView: View { 9 10 var body: some View { 11 12 let latetude = $manager.location.wrappedValue.coordinate.latitude 13 let longitude = $manager.location.wrappedValue.coordinate.longitude 14 15 Button(action: { //delete 16 clear_flag = true 17 }) 18 { 19 Image(systemName: "delete") 20 } 21 ZStack(alignment: .bottomTrailing){ 22 MapView(mapType: .standard,latetude: latetude,longitude: longitude) 23 { 24 Image(systemName: "map") 25 .resizable() 26 .frame(width: 35.0,height: 35.0, alignment: .leading) 27 } 28 } 29 } 30}
MapView.swift
1// MapView.swift 2 3import SwiftUI 4import MapKit 5 6var runPoint : [[Double]] = [[ ]] 7 8struct MapView: UIViewRepresentable{ 9 let latetude: Double 10 let longitude: Double 11 12 typealias UIViewType = MKMapView 13 14 func makeCoordinator() -> MapViewCoordinator { 15 return MapViewCoordinator() 16 } 17 18 func makeUIView(context: Context) -> MKMapView { 19 MKMapView() 20 } 21 22 func updateUIView(_ uiView: MKMapView, context: Context) { 23 uiView.delegate = context.coordinator 24 let pin = MKPointAnnotation() 25 26 if clear_flag == true{ 27 pin.coordinate.longitude = longitude 28 pin.coordinate.latitude = latetude 29 uiView.mapView.removeAnnotation(annotation) 30 }else{ 31 pin.coordinate.longitude = longitude 32 pin.coordinate.latitude = latetude 33 uiView.addAnnotation(pin) 34 } 35 36 uiView.region = MKCoordinateRegion( 37 center: pin.coordinate, 38 latitudinalMeters: 500.0, 39 longitudinalMeters:500.0) 40 } 41}
LocationManager.swift
1// LocationManager.swift 2 3import SwiftUI 4import MapKit 5 6class LocationManager: NSObject, ObservableObject, CLLocationManagerDelegate { 7 let manager = CLLocationManager() 8 @Published var location = CLLocation() 9 10 override init() { 11 super.init() 12 self.manager.delegate = self 13 self.manager.requestWhenInUseAuthorization() 14 self.manager.desiredAccuracy = kCLLocationAccuracyBest 15 self.manager.distanceFilter = 10 16 self.manager.allowsBackgroundLocationUpdates = true 17 self.manager.startUpdatingLocation() 18 } 19 20 func locationManager(_ manager: CLLocationManager, 21 didUpdateLocations locations: [CLLocation]) { 22 if map_start == true{ 23 self.location = locations.last! 24 } 25 } 26} 27

回答1件
あなたの回答
tips
プレビュー