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
}
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)
}
}