我是 swift 的新手,我正在尝试计算从用户位置到几个兴趣点的路线距离。
我不想在应用程序的这一部分中在 map 上“绘制”路线,但我只想计算路线上的距离而不是两个坐标之间的距离,然后将该距离显示为 map 上的标注。
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
和闭包中的指令。
所以现在我想知道我的想法是否是错误的,如果不是,如何才能实现我的目标。
最佳答案
(代表 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
}
}
}
...
}
}
关于swift - 在 Swift 中通过路线计算从用户到几个点的每个距离,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41389176/