我在地图上有2个位置。第一个是带有蓝点地标的用户当前位置。第二个是用红点地标指定的用户当前位置附近的餐厅位置。我想获取从用户当前位置到餐厅位置的路线。定义latitude: 38.00001 and longitude: 27.08980
之类的纬度和经度值时,我正在获取路线。
我也正在从api到每个红点地标获取每个餐厅的位置。但不要获取从用户当前位置到餐厅位置的路线。
我正在使用以下代码获取餐厅位置:
var viewModel: DetailsViewModel? {
didSet {
updateView()
}
willSet {
updateView()
}
}
func updateView() {
if let viewModel = viewModel {
detailsFoodView?.priceLabel?.text = viewModel.price
detailsFoodView?.hoursLabel?.text = viewModel.isOpen
detailsFoodView?.locationLabel?.text = viewModel.phoneNumber
detailsFoodView?.ratingsLabel?.text = viewModel.rating
detailsFoodView?.collectionView?.reloadData()
centerMap(for: viewModel.coordinate)
print("detail restaurant destination : \(viewModel.coordinate)")
title = viewModel.name
print("title: \(title)")
}
}
func centerMap(for coordinate: CLLocationCoordinate2D) {
let region = MKCoordinateRegion(center: coordinate, latitudinalMeters: 100, longitudinalMeters: 100)
let annotation = MKPointAnnotation()
annotation.coordinate = coordinate
detailsFoodView?.mapView?.addAnnotation(annotation)
detailsFoodView?.mapView?.setRegion(region, animated: true)
}
}
,然后在viewDidLoad()
中获得如下指示:
let sourceCoordinates = locationManager.location?.coordinate
问题在这里
我没有让每个餐馆的经度和纬度值设为destCoordinates
。通常,我会接受viewModel.coordinate
。
但是如果我使用
let destCoordinates = CLLocationCoordinate2D(latitude: viewModel?.coordinate.latitude, longitude: viewModel?.coordinate.longitude)
代替:
let destCoordinates = CLLocationCoordinate2D(latitude: 38.420183, longitude: 27.205559)
我得到的纬度和经度值为nil或零。
let sourcePlaceMark = MKPlacemark(coordinate: sourceCoordinates!)
let destPlaceMark = MKPlacemark(coordinate: destCoordinates)
let sourceItem = MKMapItem(placemark: sourcePlaceMark)
let destItem = MKMapItem(placemark: destPlaceMark)
let directionRequest = MKDirections.Request()
directionRequest.source = sourceItem
directionRequest.destination = destItem
directionRequest.transportType = .automobile
let directions = MKDirections(request: directionRequest)
directions.calculate(completionHandler: {response, error in
guard let response = response else {
if error != nil {
print("Something went wrong!")
}
return
}
let route = response.routes[0]
self.detailsFoodView?.mapView?.addOverlay(route.polyline, level: .aboveRoads)
let rect = route.polyline.boundingMapRect
self.detailsFoodView?.mapView?.setRegion(MKCoordinateRegion(rect), animated: true)
预期结果是当前用户位置,从蓝点地标到带红线的红点地标,如您在屏幕截图中所见。