【问题标题】:MapKit Direction to Selected annotationMapKit 到选定注释的方向
【发布时间】:2018-02-01 13:03:00
【问题描述】:

试图从用户的当前位置获取地图上选定注释的方向,但不确定如何捕捉选定的注释(当用户选择其中之一时)并显示方向。检查堆栈上的不同主题但没有很多关于如何捕捉所选注释并显示用户位置方向的新鲜信息。请告知。

import UIKit
import MapKit
import CoreLocation

class NavigationVC: UIViewController {

@IBOutlet weak var mapView: MKMapView!
let manager = CLLocationManager()
let request = MKLocalSearchRequest()

override func viewDidLoad() {
    super.viewDidLoad()

    manager.delegate = self
    manager.desiredAccuracy =   kCLLocationAccuracyBest
    manager.requestWhenInUseAuthorization()
    manager.startUpdatingLocation()


  }


 }
 //MARK: CONFIGURATION OF MAPVIEW

 extension NavigationVC: CLLocationManagerDelegate {

  func locationManager(_ manager: CLLocationManager, didUpdateLocations 
    locations: [CLLocation]) {
    let location = locations[0]
    let span: MKCoordinateSpan = MKCoordinateSpanMake(0.1, 0.1 )
    let userLocation:CLLocationCoordinate2D = 
    CLLocationCoordinate2DMake(location.coordinate.latitude, 
    location.coordinate.longitude)
    let region: MKCoordinateRegion = 
    MKCoordinateRegionMake(userLocation, span)
    mapView.setRegion(region, animated: true)
    self.mapView.showsUserLocation = true

    request.naturalLanguageQuery = "Currency exchange"
    request.region = mapView.region
    let activeSearch = MKLocalSearch(request: request)
    activeSearch.start { (response, error) in

        guard let response = response else {
            return
        }

        for item in response.mapItems {
            let annotation = MKPointAnnotation()
            annotation.coordinate = item.placemark.coordinate
            annotation.title = item.name

            DispatchQueue.main.async {
                self.mapView.addAnnotation(annotation)
            }
        }
    }


  }

  func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> 
 MKOverlayRenderer {
    let polylineRenderer = MKPolylineRenderer(overlay: overlay)
    polylineRenderer.strokeColor = UIColor.blue
    polylineRenderer.fillColor = UIColor.red
    polylineRenderer.lineWidth = 2
    return polylineRenderer


  }

}

【问题讨论】:

    标签: ios swift annotations mapkit mapkitannotation


    【解决方案1】:

    要获取地图上从您所在位置到注释的路径,请遵循以下代码:

        annotation = MKPointAnnotation()
        annotation.coordinate = CLLocationCoordinate2D(latitude: CLLocationDegrees(lat),longitude: CLLocationDegrees(lon))
        self.map?.addAnnotation(annotation)
    
    
        var route : MKRoute? = nil
    
        DispatchQueue.global(qos: .userInitiated).async { [weak self] in
            let directionRequest = MKDirectionsRequest()
            directionRequest.source = MKMapItem.forCurrentLocation();
            directionRequest.destination = MKMapItem(placemark: MKPlacemark(coordinate:(self?.annotation.coordinate)!))
            directionRequest.transportType = .automobile
            let directions = MKDirections(request: directionRequest)
    
            directions.calculate {
                (response, error) -> Void in
                guard let response = response else {
                    if let error = error {
                        print("Error: \(error)")
                    }
                    return
                }
    
                route = response.routes[0]
                if let percorso = route{
                    DispatchQueue.main.async { [weak self] in
                        self?.map?.add((percorso.polyline), level: MKOverlayLevel.aboveRoads)
                    }
                }
            }
        }
    

    你只需要选择正确的注解,也许尝试在注解上注册一个触摸监听器。

    【讨论】:

      【解决方案2】:

      使用didSelect委托方法。

      例如

      func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
          guard let annotation = view.annotation else {
              return
          }
      
          let directionRequest = MKDirectionsRequest()
          directionRequest.source = MKMapItem.forCurrentLocation()
          directionRequest.destination = MKMapItem(placemark: MKPlacemark(coordinate: annotation.coordinate))
          directionRequest.transportType = .automobile
          let directions = MKDirections(request: directionRequest)
      
          directions.calculate {
              (response, error) -> Void in
              guard let response = response else {
                  if let error = error {
                      print("Error: \(error)")
                  }
                  return
              }
      
              if !response.routes.isEmpty {
                  let route = response.routes[0]
                  DispatchQueue.main.async { [weak self] in
                      self?.mapView.add(route.polyline)
                  }
              }
          }
      }
      

      不要忘记guard 以防止崩溃。

      func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) ->
          MKOverlayRenderer {
              guard overlay is MKPolyline else {
                  return MKPolylineRenderer()
              }
          ...
      }
      

      祝你好运!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-11-02
        • 1970-01-01
        • 2013-04-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-05-03
        相关资源
        最近更新 更多