我试图在MKMapView
移动时用一条线跟踪用户的位置。问题是我目前正在尝试使用折线跟踪用户的位置,但是当用户的位置更新时,由于添加了新点,我不得不重新绘制线。这会占用大量的cpu资源,因为我经历的最大CPU使用率约为200%。如何在不使用大部分可用cpu资源的情况下在用户后面绘制路径?以下是我的代码:
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
}
答案 0 :(得分:0)
在viewDidLoad中尝试此操作,您可能希望在视图控制器中遵守CLLocationmanager Delegate。
import Mapkit
class MapViewController: UIViewController, CLLocationManagerDelegate {
override func viewDidLoad() {
let locationManager = CLLocationManager()
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
//or you can do
//locationmManager.desiredAccuracy = KCLLocationAccuracyBestForNavigation
}
}
你也可以做更多的节电或任何事情,只需检查他们的文档 KCLLocationAccuracy documentation
答案 1 :(得分:0)
你不应该这样做:
var coordinates: [CLLocationCoordinate2D] = [] {
didSet{
let polyine = MKPolyline(coordinates: coordinates, count: coordinates.count)
mapView.removeOverlays(mapView.overlays)
mapView.add(polyine)
}
}
因为他们对CPU造成很大压力。例如,以下代码如何:
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)
}
}