【发布时间】:2017-05-23 17:46:57
【问题描述】:
想法:
应用程序可让司机查看离客户最近的商店/餐厅。
我有什么:
- 保存为字符串的坐标
let clientLat = "24.449384"
let clientLng = "56.343243"
- 查找我当地所有商店的功能
我尝试保存了我当地一家商店的所有坐标,我成功了:
var coordinates: [CLLocationCoordinate2D] = [CLLocationCoordinate2D]()
func performSearch() {
coordinates.removeAll()
let request = MKLocalSearchRequest()
request.naturalLanguageQuery = "starbucks"
request.region = mapView.region
let search = MKLocalSearch(request: request)
search.start(completionHandler: {(response, error) in
if error != nil {
print("Error occured in search: \(error!.localizedDescription)")
} else if response!.mapItems.count == 0 {
print("No matches found")
} else {
print("Matches found")
for item in response!.mapItems {
self.coordinates.append(item.placemark.coordinate)
// need to sort coordinates
// need to find the closest
let annotation = MKPointAnnotation()
annotation.coordinate = item.placemark.coordinate
annotation.title = item.name
self.mapView.addAnnotation(annotation)
}
}
})
}
我需要什么:
我希望遍历坐标并找到离经纬线最近的商店(公里),然后在上面放一个别针。
更新
func performSearch() {
coordinates.removeAll()
let request = MKLocalSearchRequest()
request.naturalLanguageQuery = "starbucks"
request.region = mapView.region
let search = MKLocalSearch(request: request)
search.start(completionHandler: {(response, error) in
if error != nil {
print("Error occured in search: \(error!.localizedDescription)")
} else if response!.mapItems.count == 0 {
print("No matches found")
} else {
print("Matches found")
for item in response!.mapItems {
self.coordinates.append(item.placemark.coordinate)
let pointToCompare = CLLocation(latitude: 24.741721, longitude: 46.891440)
let storedCorrdinates = self.coordinates.map({CLLocation(latitude: $0.latitude, longitude: $0.longitude)}).sorted(by: {
$0.distance(from: pointToCompare) < $1.distance(from: pointToCompare)
})
self.coordinate = storedCorrdinates
}
let annotation = MKPointAnnotation()
annotation.coordinate = self.coordinate[0].coordinate
self.mapView.addAnnotation(annotation)
}
})
} 谢谢@brimstone
【问题讨论】:
-
coordinates是 CLLocationCoordinate2D 还是 CLLocation 的数组? -
也许你可以使用距离公式?参见This question 2 lat/longs 之间距离公式的 JavaScript 实现。 (Haversine 公式)
-
@brimstone 是
var coordinates: [CLLocationCoordinate2D] = [CLLocationCoordinate2D]()
标签: ios swift swift3 google-play