我是swift的新手,我试图计算路线上的距离,从userLocation到几个兴趣点。
我不希望,在应用程序的这一部分中,“绘制”地图上的路线,但我只想计算路线上的距离而不是两个坐标之间的距离,然后将此距离显示为地图上的标注。
POI的坐标(纬度和经度)包含在数据库中。
我在Stack Overflow上已经阅读了一些关于这个参数的帖子:
Measuring distance in meters from a drawn route in MKMapView
MKMapView get distance between coordinates on customized route
和其他教程:
http://www.technetexperts.com/mobile/draw-route-between-2-points-on-map-with-ios7-mapkit-api/ https://videos.raywenderlich.com/courses/mapkit-and-core-location/lessons/9
然后我写了这段代码:
for item in items {
if item.latitudine != "" && item.longitudine != "" {
// Point Of Interest coordinate
let latitude = Double(item.latitude!)
let longitude = Double(item.longitude!)
let itemLocation = CLLocation(latitude: latitude!, longitude: longitude!)
let itemLocationPlacemark = MKPlacemark(coordinate: itemLocation.coordinate, addressDictionary: nil)
// user coordinate
let userLocation = CLLocation(latitude: userLocation.coordinate.latitude, longitude: userLocation.coordinate.longitude)
let userLocationPlacemark = MKPlacemark(coordinate: userLocation.coordinate, addressDictionary: nil)
// create Request object
let request = MKDirectionsRequest()
request.source = MKMapItem(placemark: userLocationPlacemark)
request.destination = MKMapItem(placemark: itemLocationPlacemark)
request.requestsAlternateRoutes = false
request.transportType = .automobile
let directions = MKDirections(request: request)
directions.calculate {
[weak self] (response, error) in
if error == nil {
for route in (response?.routes)! {
let distance = (route.distance)/1000
print(distance)
}
}
}
}
}
问题是当我从第directions.calculate
行执行代码时。
程序运行该行但不执行其余的操作,不执行控件if error == nil
和闭包中的指令。
所以现在我想知道我的想法是否错误,如果没有,我怎么能实现我的目标。
答案 0 :(得分:0)
(代表OP发布解决方案)。
读取其他线程我明白问题是封闭内部的che for循环。经过多次尝试,我找到了适合我的解决方案。我在这里写它,这对其他人有用:
var counter: Int!
...
for item in itemPin {
if item.latitude != "" && item.longitude != "" {
....
....
let directions = MKDirections(request: request)
directions.calculate {
(response, error) in
print("error \(error)")
if error == nil {
counter = self.counter + 1
print(self.counter)
if self.counter >= self.itemPin.count {
let result = (response?.routes[0].distance)!/1000
}
}
}
...
}
}