简体   繁体   中英

MapKit - Trace User Location on Map Without Massive CPU Usage

I'm trying to trace the user's location with a line as they move on a MKMapView . The issue is that I'm currently trying to trace the user's location with a polyline, but when the user's location is updated I'm forced to redraw the line due to a new point being added to it. This hogs massive amounts of cpu resources, as the max cpu usage I experienced was around 200%. How should I draw a path behind the user without using a large portion of the available cpu resources? Below is my code:

var coordinates: [CLLocationCoordinate2D] = [] {
    didSet{
            let polyine = MKPolyline(coordinates: coordinates, count: coordinates.count)
            mapView.removeOverlays(mapView.overlays)
            mapView.add(polyine)
    }
}

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    coordinates.append(locations[0].coordinate)
}

func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
    let renderer = MKPolylineRenderer(overlay: overlay)

    renderer.strokeColor = UIColor.blue
    renderer.lineWidth = 5.0

    return renderer
}

try this in your viewDidLoad you might want to adhere to the CLLocationmanager Delegate in your view controller.

import Mapkit

class MapViewController: UIViewController, CLLocationManagerDelegate {
    override func viewDidLoad() {
        let locationManager = CLLocationManager()
        locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
        //or you can do
        //locationmManager.desiredAccuracy = KCLLocationAccuracyBestForNavigation
    }
}

you can also do more power savings or anything, just check their docs KCLLocationAccuracy documentation

You shouldn't do:

var coordinates: [CLLocationCoordinate2D] = [] {
    didSet{
        let polyine = MKPolyline(coordinates: coordinates, count: coordinates.count)
        mapView.removeOverlays(mapView.overlays)
        mapView.add(polyine)
    }
}

Because they put a lot of strain on CPU. For example, How about the following code:

var coordinates: [CLLocationCoordinate2D] = [] {
    didSet{
        guard coordinates.count > 1 else {
            return
        }
        let count = coordinates.count
        let start = coordinates[count-1]
        let end = coordinates[count-2]
        let polyine = MKPolyline(coordinates: [start, end], count: 2)
        mapView.add(polyine)
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM