如何在地图视图中绘制用户的路线



如何在"地图视图"中绘制用户的路线? 我的地图是工作,但路线不是绘图。 没有错误。 例如: 用户的路由

我的代码:

class ViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate {
@IBOutlet weak var mapView: MKMapView!

var locationManager: CLLocationManager!
override func viewDidLoad() {
super.viewDidLoad()
locationManager = CLLocationManager()
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.delegate = self

locationManager.requestAlwaysAuthorization()
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
locationManager.startUpdatingHeading()
mapView.delegate = self
mapView.showsUserLocation = true
mapView.mapType = MKMapType(rawValue: 0)!
mapView.userTrackingMode = MKUserTrackingMode(rawValue: 2)!
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func locationManager(manager: CLLocationManager!, didUpdateToLocation newlocation: CLLocation!, fromLocation oldLocation: CLLocation!) {
print("present location : (newlocation.coordinate.latitude), (newlocation.coordinate.longitude)")
if let oldLocationNew = oldLocation as CLLocation?{
let oldCoordinates = oldLocationNew.coordinate
let newCoordinates = newlocation.coordinate
var area = [oldCoordinates, newCoordinates]
var polyline = MKPolyline(coordinates: &area, count: area.count)
mapView.add(polyline)
}
}
func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
let pr = MKPolylineRenderer(overlay: overlay)
pr.strokeColor = UIColor.red
pr.lineWidth = 5
return pr
}

}

但它不起作用。

我假设你用下面的代表来获得最后一个位置?

func locationManager(manager: CLLocationManager!,
didUpdateToLocation newlocation: CLLocation!,
fromLocation oldLocation: CLLocation!) {

上面的委托在 iOS 6 中已弃用。现在应该使用以下方法:

func locationManager(_ manager: CLLocationManager,
didUpdateLocations locations: [CLLocation]) {

为了获得最后一个位置,只需获取数组的最后一个对象:

locations.lastObject

尝试以下代码绘制用户的路由:

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let newLocation = locations.last else {
return
}
guard let oldLocation = oldLocation else {
// Save old location
self.oldLocation = newLocation
return
}
let oldCoordinates = oldLocation.coordinate
let newCoordinates = newLocation.coordinate
var area = [oldCoordinates, newCoordinates]
let polyline = MKPolyline(coordinates: &area, count: area.count)
mapView.add(polyline)
// Save old location
self.oldLocation = newLocation
}

最新更新