我正在构建一个使用Apple Maps并且工作正常的mapView,我的segue会在地图中注入纬度和经度,我想从当前位置导航到包含lat和lon值的注释。
我设法在地图上显示当前位置并显示我的注释,但我不确定如何将当前位置设置为以下代码行中的源点。
request.source = MKMapItem(placemark: MKPlacemark(coordinate: CLLocationCoordinate2D(latitude: lat,longitude: lon)))
这使用我目前从我的segue注入的lat和lon变量。我希望request.source行是我当前的位置,lat和lon vars是我已经拥有的目的地。
我只是不确定使request.source成为我当前位置的语法。
这是我的整个VC代码供参考:
导入UIKit 导入MapKit 导入CoreLocation
类LocateVC:UIViewController,MKMapViewDelegate {
@IBOutlet weak var mapView: MKMapView!
var lat: Double!
var lon: Double!
var name: String!
var locationManager = CLLocationManager()
func checkLocationAuthorizationStatus() {
if CLLocationManager.authorizationStatus() == .authorizedWhenInUse {
mapView.showsUserLocation = true
} else {
locationManager.requestWhenInUseAuthorization()
}
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
checkLocationAuthorizationStatus()
}
override func viewDidLoad() {
super.viewDidLoad()
annotation.coordinate = CLLocationCoordinate2D(latitude: lat, longitude: lon)
mapView.addAnnotation(annotation)
let request = MKDirectionsRequest()
request.source = MKMapItem(placemark: MKPlacemark(coordinate: CLLocationCoordinate2D(latitude: lat,longitude: lon)))
request.destination = MKMapItem(placemark: MKPlacemark(coordinate: CLLocationCoordinate2D(latitude: lat,longitude: lon)))
request.requestsAlternateRoutes = true
request.transportType = .automobile
let directions = MKDirections(request: request)
directions.calculate {[unowned self] response, error in
guard let unwrappedResponse = response else { return }
for route in unwrappedResponse.routes {
self.mapView.add(route.polyline)
self.mapView.setVisibleMapRect(route.polyline.boundingMapRect, animated: true)
}
}
}
func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
let renderer = MKPolylineRenderer(polyline: overlay as! MKPolyline)
renderer.strokeColor = UIColor.blue
return renderer
}
let regionRadius: CLLocationDistance = 1000
let annotation = MKPointAnnotation()
func centerMapOnLocation(location: CLLocation) {
let coordinateRegion = MKCoordinateRegionMakeWithDistance(location.coordinate, regionRadius * 2.0, regionRadius * 2.0)
mapView.setRegion(coordinateRegion, animated: true)
mapView.showsUserLocation = true
}
答案 0 :(得分:1)
当位置管理器检索当前位置时,您必须覆盖CLLocationManager.didUpdateLocations以获得通知。您必须应用CLLocationManager委托。
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
let location = locations.last as CLLocation
let center = CLLocationCoordinate2D(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude)
let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))
self.map.setRegion(region, animated: true)
}