在两个A和B位置之间路由

时间:2017-11-13 01:20:48

标签: swift xcode core-location

没有错误,但我无法从当前位置获取我搜索的位置。有人可以请帮助。它说了这一点,我点击了汽车logo to get directions: MKDirectionsErrorCode=7, NSLocalizedDescription=Directions Not Available}

我只是错过了朝着方向前进的路线。当我点击汽车标志时,它只是没有做任何事情,只是缩小到我当前的位置。我错过了什么或做错了什么?

这是我的代码:

  protocol HandleMapSearch {
        func dropPinZoomIn(placemark:MKPlacemark)
    }

    class ViewController: UIViewController  {

    @IBOutlet weak var mapView: MKMapView! // Handle the Map Kit View

    var selectedPin:MKPlacemark? = nil //Any incoming placemarks

    // Destination for directions*********
    var destination:MKMapItem = MKMapItem()
    var MyPosition = CLLocationCoordinate2D()

    var resultSearchController:UISearchController? = nil // Keep the UISearchController in memory after it's created

    var locationManager = CLLocationManager()  // Core Location

    override func viewDidLoad() {
        super.viewDidLoad()

        mapView.delegate = self
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyBest  // Accuracy level
        locationManager.requestWhenInUseAuthorization()  // Triggers the location permission dialog
        locationManager.startUpdatingLocation()
        //locationManager.requestLocation() // Trigers a one-time location request


        // Set up the search results table
        let locationSearchTable = storyboard!.instantiateViewController(withIdentifier: "LocationSearchTable") as! LocationSearchTable
        resultSearchController = UISearchController(searchResultsController: locationSearchTable)
        resultSearchController?.searchResultsUpdater = locationSearchTable

        // Set up the search bar
        let searchBar = resultSearchController!.searchBar
        searchBar.sizeToFit()
        searchBar.placeholder = "Search for places"
        navigationItem.titleView = resultSearchController?.searchBar

        // Configure the UISearchController appearance
        resultSearchController?.hidesNavigationBarDuringPresentation = false
        resultSearchController?.dimsBackgroundDuringPresentation = true
        definesPresentationContext = true

        locationSearchTable.mapView = mapView // Passes along a handle of the mapView

        locationSearchTable.handleMapSearchDelegate = self // Handles the map search

    }


    //Getting direction of location
    @objc func getDirections(sender: AnyObject){
       if let selectedPin = selectedPin {
            let mapItem = MKMapItem(placemark: selectedPin)
            //let launchOptions = [MKLaunchOptionsDirectionsModeKey : MKLaunchOptionsDirectionsModeDriving]
            //mapItem.openInMaps(launchOptions: launchOptions)

            let request = MKDirectionsRequest()
            request.source = MKMapItem.forCurrentLocation()

            request.destination = destination
            request.requestsAlternateRoutes = false

            let directions = MKDirections(request: request)

        // 8.
        directions.calculate {
            (response, error) -> Void in

            guard let response = response else {
                if let error = error {
                    print("Error: \(error)")
                }

                return
            }

            let route = response.routes[0]
            self.mapView.add((route.polyline), level: MKOverlayLevel.aboveRoads)

            let rect = route.polyline.boundingMapRect
            self.mapView.setRegion(MKCoordinateRegionForMapRect(rect), animated: true)
        }

    }
       /*
        directions.calculate(completionHandler: {(response: MKDirectionsResponse!, error: Error!) in

            if error != nil {
                print("Error \(error)")

            } else {

                self.displayRout(response)

                var overlays = self.mapView.overlays

                for route in response.routes {

                    self.mapView.add(route.polyline, level: MKOverlayLevel.aboveRoads)

                    for next in route.steps {
                        print(next.instructions)
                    }
                }
            }
        })

    }
    */

        func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
            let renderer = MKPolylineRenderer(overlay: overlay)
            renderer.strokeColor = UIColor.blue
            renderer.lineWidth = 4.0

            return renderer
        }
    }
        //destination = MKMapItem(placemark: selectedPin!)

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}


extension ViewController : CLLocationManagerDelegate {
    // When user responds to the permission dialog
    private func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
        if status == .authorizedWhenInUse {
        locationManager.requestLocation()
    }
}


    // When location information comes back (Zoom to the user's current location)
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        if let location = locations.first {

            //****
            MyPosition = location.coordinate
            locationManager.stopUpdatingLocation()

            let span = MKCoordinateSpanMake(0.01, 0.01)
            let region = MKCoordinateRegion(center: location.coordinate, span: span)
            mapView.setRegion(region, animated: true)

    }


}

    // Print out the error
    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        print("Error finding location: \(error.localizedDescription)")
    }
}

// Searches the location and city/state
extension ViewController: HandleMapSearch {
    func dropPinZoomIn(placemark:MKPlacemark){
        // cache the pin
        selectedPin = placemark
        // clear existing pins
        mapView.removeAnnotations(mapView.annotations)
        let annotation = MKPointAnnotation()
        annotation.coordinate = placemark.coordinate
        annotation.title = placemark.name
        if let city = placemark.locality,
            let state = placemark.administrativeArea {
            annotation.subtitle = "\(city) \(state)"
        }
        mapView.addAnnotation(annotation)
        let span = MKCoordinateSpanMake(0.01, 0.01)
        let region = MKCoordinateRegionMake(placemark.coordinate, span)
        mapView.setRegion(region, animated: true)
    }
}

// Shows Pins and Car Logo
extension ViewController : MKMapViewDelegate {
    func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView?{
        if annotation is MKUserLocation {
            //return nil so map view draws "blue dot" for standard user location
            return nil
        }
        let reuseId = "pin"
        var pinView = mapView.dequeueReusableAnnotationView(withIdentifier: reuseId) as? MKPinAnnotationView
        pinView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
        pinView?.pinTintColor = UIColor.red
        pinView?.canShowCallout = true
        let smallSquare = CGSize(width: 30, height: 30)
        let button = UIButton(frame: CGRect(origin: CGPoint.zero, size: smallSquare))
        button.setBackgroundImage(UIImage(named: "Car"), for: .normal)
        button.addTarget(self, action: #selector(getDirections), for: .touchUpInside)

        pinView?.leftCalloutAccessoryView = button
        return pinView


    }

}

1 个答案:

答案 0 :(得分:2)

看看下面的代码以供参考,希望它有所帮助:

1使用两个位置作为源和目标,并根据位置绘制路径

import UIKit
import CoreLocation
import MapKit

class ViewController: UIViewController,  MKMapViewDelegate {

    @IBOutlet weak var mapView: MKMapView!
    override func viewDidLoad() {
        super.viewDidLoad()

        mapView.delegate = self
        // Do any additional setup after loading the view, typically from a nib.

        let sourceLocation = CLLocationCoordinate2D(latitude: 40.759011, longitude: -73.984472)
        let destinationLocation = CLLocationCoordinate2D(latitude: 40.748441, longitude: -73.985564)

        // 3.
        let sourcePlacemark = MKPlacemark(coordinate: sourceLocation, addressDictionary: nil)
        let destinationPlacemark = MKPlacemark(coordinate: destinationLocation, addressDictionary: nil)

        // 4.
        let sourceMapItem = MKMapItem(placemark: sourcePlacemark)
        let destinationMapItem = MKMapItem(placemark: destinationPlacemark)

        // 5.
        let sourceAnnotation = MKPointAnnotation()
        sourceAnnotation.title = "Times Square"

        if let location = sourcePlacemark.location {
            sourceAnnotation.coordinate = location.coordinate
        }


        let destinationAnnotation = MKPointAnnotation()
        destinationAnnotation.title = "Empire State Building"

        if let location = destinationPlacemark.location {
            destinationAnnotation.coordinate = location.coordinate
        }

        // 6.
        self.mapView.showAnnotations([sourceAnnotation,destinationAnnotation], animated: true )

        // 7.
        let directionRequest = MKDirectionsRequest()
        directionRequest.source = sourceMapItem
        directionRequest.destination = destinationMapItem
        directionRequest.transportType = .walking

        // Calculate the direction
        let directions = MKDirections(request: directionRequest)

        // 8.
        directions.calculate {
            (response, error) -> Void in

            guard let response = response else {
                if let error = error {
                    print("Error: \(error)")
                }

                return
            }

            let route = response.routes[0]
            self.mapView.add((route.polyline), level: MKOverlayLevel.aboveRoads)

            let rect = route.polyline.boundingMapRect
            self.mapView.setRegion(MKCoordinateRegionForMapRect(rect), animated: true)
        }
    }
    func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
        let renderer = MKPolylineRenderer(overlay: overlay)
        renderer.strokeColor = UIColor.blue
        renderer.lineWidth = 4.0

        return renderer
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

输出:

enter image description here