I have an array with the coordinates of the route which is displayed on the mapView. I can not draw a line my coordinates on the route.
this is my class:
i import the needed modules
import UIKit
import MapKit
import CoreLocation
then here is my class
class MapViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate {
var locationManager = CLLocationManager()
var location: [(Double, Double)]?
var placeAnnotation: [String]?
var sourceLocation: CLLocationCoordinate2D!
var indexPoint = 0
@IBOutlet weak var mapView: MKMapView!
let regionRadius: CLLocationDistance = 1000
func centerMapOnLocation(location: CLLocation) {
let coordinateRegion = MKCoordinateRegionMakeWithDistance(location.coordinate, regionRadius, regionRadius)
mapView.setRegion(coordinateRegion, animated: true)
}
override func viewDidLoad() {
super.viewDidLoad()
mapView.delegate = self
drawPlaceMark()
}
func drawPlaceMark() {
for (x,y) in location! {
sourceLocation = CLLocationCoordinate2D(latitude: x, longitude: y)
let destinationPlacemark = MKPlacemark(coordinate: sourceLocation, addressDictionary: nil)
let destinationMapItem = MKMapItem(placemark: destinationPlacemark)
let sourceAnnotation = MKPointAnnotation()
sourceAnnotation.title = placeAnnotation?[indexPoint]
indexPoint = indexPoint + 1
if let location = destinationPlacemark.location {
sourceAnnotation.coordinate = location.coordinate
}
self.mapView.showAnnotations([sourceAnnotation,sourceAnnotation], animated: true )
// Calculate the direction and draw line
let directionRequest = MKDirectionsRequest()
directionRequest.source = destinationMapItem
directionRequest.destination = destinationMapItem
directionRequest.transportType = .walking
let directions = MKDirections(request: directionRequest)
directions.calculate {
(response, error) -> Void in
guard let response = response else {
if let error = error {
print("Error: \(error)")
}
return
}
let route = response.routes[0]
self.mapView.add((route.polyline), level: MKOverlayLevel.aboveRoads)
let rect = route.polyline.boundingMapRect
self.mapView.setRegion(MKCoordinateRegionForMapRect(rect), animated: true)
}
}
}
}
if any one can help, please tell me how to do it in the right way and correctly.