【发布时间】:2017-02-28 15:40:56
【问题描述】:
好的,希望是一个简单的快速问题。
我正在构建一个使用 Apple Maps 并且工作正常的 mapView,我的 segue 将纬度和经度注入到地图中,我想从当前位置导航到包含 lat 和 lon 值的注释。
我已设法在地图上显示当前位置并显示我的注释,但我不确定如何在以下代码行中将当前位置设置为源点。
request.source = MKMapItem(placemark: MKPlacemark(coordinate: CLLocationCoordinate2D(latitude: lat,longitude: lon)))
这使用我当前从我的 segue 注入的 lat 和 lon 变量。我希望 request.source 行成为我当前的位置,lat 和 lon 变量用于我已经拥有的目的地。
我只是不确定将 request.source 设为当前位置的语法。
这是我的整个 VC 代码供参考:
导入 UIKit 导入 MapKit 导入核心位置
类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
}
【问题讨论】: