当用户点击图钉时,我如何启动从用户位置固定注释的方向?
Posted
技术标签:
【中文标题】当用户点击图钉时,我如何启动从用户位置固定注释的方向?【英文标题】:How do i initiate directions to pin annotations from user location when the user taps the pin? 【发布时间】:2020-11-05 04:00:29 【问题描述】:我有一个 mkannotationview 来生成我的注释点。我已经设置了用户位置权限,因此如果启用了授权,则会显示用户的位置。我现在希望当用户单击 pin 时,生成从用户位置到 pin 的最快路线(仅在启用位置授权时)。
【问题讨论】:
【参考方案1】:假设您已经创建了位置管理器
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
【讨论】:
以上是关于当用户点击图钉时,我如何启动从用户位置固定注释的方向?的主要内容,如果未能解决你的问题,请参考以下文章