Adding a route to a MKMapView

前端 未结 2 525
情深已故
情深已故 2020-12-18 09:01

I\'m trying to add a routing feature to an app I\'m working on. I found Craig Spitzkoff\'s article on how to draw lines on an MKMapView which works pretty good.

2条回答
  •  别那么骄傲
    2020-12-18 09:55

    I know this is an old question, but nowadays you can also use MapKit’s MKDirections. For example, here’s a routine to search for some searchString and then add directions to the first hit on to your map view:

    let request = MKLocalSearch.Request()
    request.region = mapView.region
    request.naturalLanguageQuery = searchString
    
    let search = MKLocalSearch(request: request)
    search.start { response, _ in
        guard let mapItem = response?.mapItems.first else { return }
    
        let request = MKDirections.Request()
        request.source = MKMapItem.forCurrentLocation()
        request.destination = mapItem
        let directions = MKDirections(request: request)
        directions.calculate { response, error in
            guard let routes = response?.routes else { return }
    
            let overlays = routes.map { $0.polyline }
            self.mapView.addOverlays(overlays)
        }
    }
    

    To make sure this is rendered on your map, you would make sure to set your map view’s delegate property (either in IB or programmatically) and then implement mapView(_:rendererFor:):

    extension MapViewController: MKMapViewDelegate {
        func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
            let renderer = MKPolylineRenderer(overlay: overlay)
            renderer.strokeColor = .init(red: 0, green: 0, blue: 1, alpha: 0.7)
            return renderer
        }
    }
    

提交回复
热议问题