当用户点击pin时,我如何从用户位置启动pin注释的指示



我有一个生成注释点的mkannotationview。我已经设置了用户位置权限,所以如果启用了授权,就会显示用户的位置。现在,我希望当用户单击pin时,从用户的位置生成到pin的最快路径(仅当启用位置授权时(。

假设您已经创建了一个位置管理器

var currentPlacemark: CLPlacemark? 
@IBAction func getDirectionsTapped(_ sender: Any) { //action from storyboard to viewcontroller (command + drag)
getAddress()
}
func getAddress(){
let overlays = mapView.overlays // these lines of code
mapView.removeOverlays(overlays) // are to clean up your mapview when
locationManager.stopUpdatingLocation() // a new directions request is made

guard let currentPlacemark = currentPlacemark else {
return
}

let directionRequest = MKDirections.Request()
let destinationPlacemark = MKPlacemark(placemark: currentPlacemark)

directionRequest.source = MKMapItem.forCurrentLocation()
directionRequest.destination = MKMapItem(placemark: destinationPlacemark)

directionRequest.transportType = ."[your transport type]"
let directions = MKDirections(request: directionRequest)
directions.calculate { (directionsResponse, error) in
guard let directionsResponse = directionsResponse else {
if let error = error { // unused variable
print("Error")
}
return
}
for route in directionsResponse.routes{ //for loop to show all possible routes or let route = directionsResponse.route[0] to get first route only
self.mapView.addOverlay(route.polyline, level: .aboveRoads) //level is optional
self.mapView.setVisibleMapRect(route.polyline.boundingMapRect, animated: true)
}

}
locationManager.startUpdatingLocation()
}
func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
if let location = view.annotation as? [pointannotation name] {
self.currentPlacemark = MKPlacemark(coordinate: location.coordinate)
}
}
func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
let render = MKPolylineRenderer(overlay: overlay as! MKPolyline)
render.strokeColor = //choose a color
return render
}

最新更新