使用MKDirections获取地图方向和路线不起作用

时间:2015-08-16 16:50:02

标签: ios swift maps

我试图通过点击按钮为用户提供导航方向。但由于某种原因,它似乎没有起作用。

@IBAction func directionToDestination(sender: AnyObject) {
        getDirections()
    }

    func getDirections(){
        let request = MKDirectionsRequest()
        let destination = MKPlacemark(coordinate: CLLocationCoordinate2DMake(place.latitude, place.longitude), addressDictionary: nil)
        request.setSource(MKMapItem.mapItemForCurrentLocation())
        request.setDestination(MKMapItem(placemark: destination))
        request.transportType = MKDirectionsTransportType.Automobile
        var directions = MKDirections(request: request)
        directions.calculateDirectionsWithCompletionHandler({(response:
            MKDirectionsResponse!, error: NSError!) in

            if error != nil {
                // Handle error
            } else {
                self.showRoute(response)
            }

        })
    }

        func showRoute(response: MKDirectionsResponse) {

           for route in response.routes as! [MKRoute] {

                placeMap.addOverlay(route.polyline,level: MKOverlayLevel.AboveRoads)
                for step in route.steps {
                    println(step.instructions)
                }
            }
    }

            func mapView(mapView: MKMapView!, rendererForOverlay
                overlay: MKOverlay!) -> MKOverlayRenderer! {
                    let renderer = MKPolylineRenderer(overlay: overlay)

                    renderer.strokeColor = UIColor.blueColor()
                    renderer.lineWidth = 5.0
                    return renderer
            }

这是viewDidLoad()看起来

的方式
manager = CLLocationManager()
        manager.delegate = self
        manager.requestWhenInUseAuthorization()
        placeMap.delegate = self

有人可以指出我在swift中使用示例代码做错了吗?

2 个答案:

答案 0 :(得分:0)

我不知道你是否在plist项目中添加了两个必需的字符串。

 NSLocationWhenInUseUsageDescription
 NSLocationAlwaysUsageDescription

答案 1 :(得分:0)

这是一个完整的工作示例,用于获取用户位置和获取目的地坐标的路线。

import UIKit
import MapKit

class ViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate {
@IBOutlet weak var mapView: MKMapView!

var locationManager = CLLocationManager()

override func viewDidLoad() {
    super.viewDidLoad()
    
    mapView.showsUserLocation = true
    mapView.delegate = self
    locationManager.delegate = self
    locationManager.desiredAccuracy = kCLLocationAccuracyBest
    locationManager.requestWhenInUseAuthorization()
    locationManager.startUpdatingLocation()
}

@IBAction func directionToDestinationButtonPressed(_ sender: UIButton) {
    guard let userLocationCoordinate = UserLocation.shared.location?.coordinate else { return }
    let directionRequest = MKDirections.Request()
    directionRequest.source = MKMapItem(
        placemark: MKPlacemark(
            coordinate: userLocationCoordinate
        )
    )
    directionRequest.destination = MKMapItem(
        placemark: MKPlacemark(
            coordinate: CLLocationCoordinate2D(latitude: 47.6205, longitude: -122.3493)
        )
    )
    directionRequest.transportType = .automobile
    let directions = MKDirections(request: directionRequest)
    directions.calculate { (response, error) in
        guard let response = response else { return }
        let route = response.routes.first
        if let line = route?.polyline {
            self.mapView.addOverlay(line, level: .aboveRoads)
        }
    }
}


//MARK: - MKMapViewDelegate
func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
    if let polyLine = overlay as? MKPolyline {
        let lineRenderer = MKPolylineRenderer(polyline: polyLine)
        lineRenderer.strokeColor = .red
        lineRenderer.lineWidth = 3
        return lineRenderer
    }
    
    return MKOverlayRenderer()
}

//MARK: - CLLocationManagerDelegate
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    UserLocation.shared.location = locations.first
}

func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
    switch status {
    case .authorizedWhenInUse:
        locationManager.startUpdatingLocation()
        locationManager.startUpdatingHeading()
    case .denied:
        UserLocation.shared.location = nil
        locationManager.requestWhenInUseAuthorization()
    case .notDetermined:
        UserLocation.shared.location = nil
        locationManager.requestWhenInUseAuthorization()
    default:
        break
    }
}

func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
    print("Location Manager Error -> \(String(describing: error.localizedDescription))")
}
}

添加这个类来保存用户位置

class UserLocation {
    static let shared = UserLocation()
    var location: CLLocation?
}

在 Info.plist 中添加这个键和值

<key>NSLocationWhenInUseUsageDescription</key>
<string>Location Usage Description Shown To The User</string>