How to draw a route between two locations using MapKit in Swift?

后端 未结 4 577
孤独总比滥情好
孤独总比滥情好 2020-12-08 07:51

How can I draw a route between user\'s current location to a specific location using MapKit in Swift?

I searched a lot, but didn\'t find any helpful

4条回答
  •  难免孤独
    2020-12-08 08:15

    class MapController: UIViewController, MKMapViewDelegate {
    
    func showRouteOnMap() {
        let request = MKDirectionsRequest()
        request.source = MKMapItem(placemark: MKPlacemark(coordinate: annotation1.coordinate, addressDictionary: nil))
        request.destination = MKMapItem(placemark: MKPlacemark(coordinate: annotation2.coordinate, addressDictionary: nil))
        request.requestsAlternateRoutes = true
        request.transportType = .Automobile
    
        let directions = MKDirections(request: request)
    
        directions.calculateDirectionsWithCompletionHandler { [unowned self] response, error in
            guard let unwrappedResponse = response else { return }
    
            if (unwrappedResponse.routes.count > 0) {
                self.mapView.addOverlay(unwrappedResponse.routes[0].polyline)
                self.mapView.setVisibleMapRect(unwrappedResponse.routes[0].polyline.boundingMapRect, animated: true)
            }
        }
    }
    
    func mapView(mapView: MKMapView!, rendererForOverlay overlay: MKOverlay!) -> MKOverlayRenderer! {
        if overlay is MKPolyline {
                var polylineRenderer = MKPolylineRenderer(overlay: overlay)
                polylineRenderer.strokeColor = UIColor.blueColor()
            polylineRenderer.lineWidth = 5
            return polylineRenderer
        }
        return nil
    }
    

    The return is an array of possible routes, usually we just want to show the first. The annotations are the map annotations.

提交回复
热议问题