微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

SwiftUI Polyline 不会更新以跟随用户移动 LocationViewModel.swiftSecondMap.swiftTrackerDetailCard

如何解决SwiftUI Polyline 不会更新以跟随用户移动 LocationViewModel.swiftSecondMap.swiftTrackerDetailCard

我花了很多时间研究这个问题并尝试了一些方法,但没有一个我有用。这位 Swift 菜鸟将不胜感激任何帮助。

为了获得更多 MapKit 体验,我尝试在地图上用一条跟随用户移动的折线向用户展示他们的路径,类似于运行跟踪用户的应用程序。我可以很好地跟踪用户,但我无法显示带有随着用户移动而更新的折线的实时地图。关闭地图并返回时,折线将更新为缺少的坐标。 ** 我怀疑我的问题的答案与此有关:) **

Showing the polyline stops updating

显示地图加载后且用户远离折线的图像。关闭地图并重新打开重新绘制折线的缺失点

Locationviewmodel.swift

    var locationArray: [CLLocation] = []
    var coordArray: [CLLocationCoordinate2D] = []
(...)
    var coordinates2D:[CLLocationCoordinate2D] {
        var coordArray = [CLLocationCoordinate2D]()
        
        for c in locationArray {
            let lat = c.coordinate.latitude
            let long = c.coordinate.longitude
            
            let x = CLLocationCoordinate2D(latitude: lat,longitude: long)
            
            coordArray.append(x)
            
        }
        return coordArray
    }
(...)
    func locationManager(_ manager: CLLocationManager,didUpdateLocations locations: [CLLocation]) {
       
        for newLocation in locations {
          let howRecent = newLocation.timestamp.timeIntervalSinceNow
          guard newLocation.horizontalAccuracy < 20 && abs(howRecent) < 10 else { continue }
          
            speeds.append(contentsOf: locationArray.map{$0.speed}) //append all new speed updates to the array
            
            altitude.append(contentsOf: locationArray.map{$0.altitude}) //append all new speed updates to the array

           
            locationArray.append(newLocation)
        }

SecondMap.swift


import Foundation

import SwiftUI
import MapKit

struct SecondMap: UIViewRepresentable {
    typealias UIViewType = MKMapView
    
    @EnvironmentObject var model: LocationsModel
    
    @State var regionZoom = LocationService.sharedLocinstance.locationManager.location?.coordinate
    
    func makeUIView(context: Context) -> MKMapView {
        
        let mapView = MKMapView()
        
        mapView.showsUserLocation = true
        mapView.userTrackingMode = .followWithheading
        
        return mapView
        
    }
    
    func updateUIView(_ uiView: MKMapView,context: Context) {
        
//        uiView.removeAnnotation(uiView.annotations)
//        uiView.showAnnotations(self.locations,animated: true)
        if regionZoom != nil {
            
            let span = MKCoordinateSpan(latitudeDelta: 0.005,longitudeDelta: 0.005)
            let region = MKCoordinateRegion(center: regionZoom!,span: span)
            uiView.setRegion(region,animated: true)
            
        }
        
        
        let polyline = MKpolyline(coordinates: model.coordinates2D,count: model.coordinates2D.count)
        uiView.removeOverlay(polyline)
        uiView.addOverlay(polyline)
        
        uiView.delegate = context.coordinator
    }
    
    static func dismantleUIView(_ uiView: MKMapView,coordinator: ()) {
//        uiView.removeAnnotation(uiView.annotations)
    }
    
    //MARK: - Create Coordinator Class
    func makeCoordinator() -> Coordinator {
        return Coordinator()
    }

    class Coordinator: NSObject,MKMapViewDelegate {

        func mapView(_ mapView: MKMapView,viewFor annotation: MKAnnotation) -> MKAnnotationView? {

            // If the annotation is the user dot then return nil
            if annotation is MKUserLocation {
                return nil
            }

            // Create an annotation view
            let annotationView = MKMarkerAnnotationView(annotation: annotation,reuseIdentifier: "business")

            annotationView.canShowCallout = false
            annotationView.rightCalloutAccessoryView = UIButton(type: .detaildisclosure)
            annotationView.isHidden = true
            return annotationView

        }

        func mapView(_ mapView: MKMapView,rendererFor overlay: MKOverlay) -> MKOverlayRenderer {

            if let routepolyline = overlay as? MKpolyline {
                let renderer = MKpolylineRenderer(polyline: routepolyline)
                renderer.strokeColor = UIColor.blue
                renderer.linewidth = 7
                return renderer
            }

            return MKOverlayRenderer()
        }

    }
    
    
}

TrackerDetailCard

import SwiftUI
import MapKit

struct TrackerDetailView: View {
    
    @EnvironmentObject var model: LocationsModel
    
    @State var isMapShowing = false
    
    
//    @State var regionZoom = LocationService.sharedLocinstance.locationManager.location?.coordinate
    
    var body: some View {
        NavigationView {
            
            if !isMapShowing {
                
                vstack(alignment: .leading) {
                    HStack{
                        
                        Text("Map info and stuff")
                        
                        Button {
                            self.isMapShowing = true
                        } label: {
                            Text("Launch Map")
                                .font(.system(size: 12))
                                .foregroundColor(.gray)
                        }
                        .buttonStyle(NEUMORPHISM_BUTTON())
                        
                    } // HSTACK END
                    HStack {
                        
                        Button {
                            LocationService.sharedLocinstance.locationManager.startUpdatingLocation()
                        } label: {
                            Text("Record runs")
                                .font(.system(size: 12))
                                .foregroundColor(.gray)
                        }
                        .buttonStyle(NEUMORPHISM_BUTTON_SQ())
                        
                        Button {
                            LocationService.sharedLocinstance.locationManager.stopUpdatingLocation()
                        } label: {
                            Text("End recording")
                                .font(.system(size: 12))
                                .foregroundColor(.gray)
                        }
                        .buttonStyle(NEUMORPHISM_BUTTON_SQ())
                        
                        Button {
                            print("button tapped")
                        } label: {
                            Text("Something")
                                .font(.system(size: 12))
                                .foregroundColor(.gray)
                        }
                        .buttonStyle(NEUMORPHISM_BUTTON_SQ())
                        
                    }
                    vstack{
                        
                        Text("Average Speed: \(model.avgSpeed)")
                        Text("Top Speed: \(model.topSpeed)")
//                        Text("Top Speed: \(model.altitude)")
                        
                    }
                    Spacer()
                } // vstaCK END
                .navigationBarHidden(true)
            }
            else{
                
                ZStack(alignment: .top){
                    // show map
                    SecondMap()
                        .ignoresSafeArea()
                    
                    ZStack{
                        Rectangle()
                            .foregroundColor(.white)
                            .cornerRadius(5)
                            .frame(height: 48)
                        
                        HStack{
                            Image(systemName: "location")
                            Spacer()
                            Button("Back to home") {
                                self.isMapShowing = false
                            }
                            
                        }.padding()
                        
                    }.padding()
                }
                
            }
            
            
        } // BODY END
        
    }
    
    
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。