当用户点击图钉时,如何从用户位置启动图钉注释的方向?

问题描述

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

解决方法

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

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
}