我如何在`mapView中绘制用户路线? 我的地图正在工作,但路线未绘制。 没有错误。 例如: User's route
我的代码:
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
}
}
但是它不起作用。
答案 0 :(得分:0)
我假设您使用以下代理人来获得最后职位?
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
}