Я пытаюсь добавить полилинию для маршрута в MapView из местоположения A в местоположение B (которое является текущим местоположением GPS пользователя), поэтому маршрут/полилиния сможет следовать из заданного местоположения A туда, где находится текущий пользователь в (местоположение B) на лету.
Сейчас мой оверлей не работает. Я просмотрел несколько других потоков SO на MKPolylineView, но когда я попытался реализовать их код (который также ниже) маршрут/линии по-прежнему не отображаются. Я новичок в iOS, поэтому я все еще знакомлюсь со Swift/mapKit.
Вот что у меня есть до сих пор: (изменено, чтобы показать важные части)
class ViewController: UIViewController, CLLocationManagerDelegate {
@IBOutlet weak var setLocButton: UIButton!
@IBOutlet weak var mapView: MKMapView!
var locationManager: CLLocationManager = CLLocationManager()
var carLat = 36.136111, carLong = -80.279462
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [CLLocation]!) { //AnyObject->CLLocation
var latestLocation: CLLocation = locations[locations.count - 1]
//Displaying location A on mapView
let carCoords = CLLocationCoordinate2D(latitude: carLat, longitude: carLong)
let region = MKCoordinateRegion(center: carCoords, span: MKCoordinateSpan(latitudeDelta: 0.0035, longitudeDelta: 0.0035))
mapView.mapType = MKMapType.Hybrid
mapView.setRegion(region, animated: true)
//Attempting to display route information on mapView
mapView.showsUserLocation = true
var locations = [CLLocation(latitude: carLat, longitude: carLong), CLLocation(latitude: latestLocation.coordinate.latitude, longitude: latestLocation.coordinate.latitude)]
var coordinates = locations.map({(location: CLLocation) -> CLLocationCoordinate2D in return location.coordinate})
var polyline = MKPolyline(coordinates: &coordinates, count: locations.count)
self.mapView.addOverlay(polyline)
}
//rendererForOverlay
func mapView(mapView: MKMapView!, rendererForOverlay overlay: MKOverlay!) -> MKOverlayRenderer! {
if overlay is MKPolyline {
/* Does not get called */
print("rendererForOverlay")
var polylineRenderer = MKPolylineRenderer(overlay: overlay)
polylineRenderer.strokeColor = UIColor.blueColor()
polylineRenderer.lineWidth = 5
return polylineRenderer
}
return nil
}
Я также нашел другой пример использования MKDirections, который кажется более идеальным, поскольку позволяет мне установить тип транспорта (MKDirectionsTransportType.Walking). У меня тоже проблемы с рисованием маршрутов с этими инструкциями.
Используя второй набор инструкций, вот что я получил после устранения некоторых ошибок, о которых меня предупредил Xcode:
var route: MKRoute?
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [CLLocation]!) { //AnyObject->CLLocation
var latestLocation: CLLocation = locations[locations.count - 1] //AnyObject
/*
...
*/
//carLocation = Location A; currentLocation = location B
var directionsRequest = MKDirectionsRequest()
let carLocation = MKPlacemark(coordinate: carCoords, addressDictionary: nil)
var currentLocation = MKPlacemark(coordinate: CLLocationCoordinate2D(latitude: coorLat, longitude: coorLong), addressDictionary: nil)
directionsRequest.source = MKMapItem(placemark: currentLocation)
directionsRequest.destination = MKMapItem(placemark: carLocation)
directionsRequest.transportType = MKDirectionsTransportType.Walking
var directions = MKDirections(request: directionsRequest)
directions.calculateDirectionsWithCompletionHandler {
(response, error) -> Void in
if error == nil {
self.route = response!.routes[0] as? MKRoute
self.mapView.addOverlay((self.route?.polyline)!)
}
}
}
func mapView(mapView: MKMapView!, rendererForOverlay overlay: MKOverlay!) -> MKOverlayRenderer! {
/* Does not get executed as well */
print("RendererForOverLay")
var myLineRenderer = MKPolylineRenderer(polyline: (route?.polyline)!)
myLineRenderer.strokeColor = UIColor.redColor()
myLineRenderer.lineWidth = 3
return myLineRenderer
}
Я как-то неправильно связываю rendererForOverlay, поскольку он не вызывается в обоих случаях?
func mapView(mapView: MKMapView!, rendererForOverlay overlay: MKOverlay!) -> MKOverlayRenderer!
, в качестве делегата для вашего mapView? Как это сделано вfunc viewDidLoad
на примере вашей ссылки? Этот код:myMap.delegate = self
- person sofacoder   schedule 10.02.2016