我需要找到当前位置附近最近的城市。你能告诉我如何在我的项目中将坐标填充到一个数组中,以及如何计算我的位置和我周围最近的位置之间的距离。我必须以(KM)和城市名称显示距离,以便用户可以选择最适合他的城市。我还需要从json文件中调用代码中的坐标和名称 我的JSON文件是:
{
"City A": {
"Position": {
"Longitude": 9.96233,
"Latitude": 49.80404
}
},
"City B": {
"Position": {
"Longitude": 6.11499,
"Latitude": 50.76891
}
},
"City C": {
"Position": {
"Longitude": 6.80592,
"Latitude": 51.53548
}
到目前为止和我的功能:
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let userlocation:CLLocation = locations[0] as CLLocation
manager.stopUpdatingLocation()
let location = CLLocationCoordinate2D(latitude: userlocation.coordinate.latitude, longitude: userlocation.coordinate.longitude)
let span = MKCoordinateSpanMake(0.5, 0.5)
let region = MKCoordinateRegion(center: location, span: span)
Mapview.setRegion(region, animated: true)
let locations = ["42.6977,23.3219","43.6977,24.3219"]
let distanceMeters = userlocation.distanceFromLocation(CLLocation(latitude: 42.6977,longitude: 23.3219))
let distanceKilometers = distanceMeters / 1000.00
let roundedDistanceKilometers = String(Double(round(100 * distanceKilometers) / 100)) + " km"
// var distanceMeter = NSString(format: "\(distanceKilometers)km")
答案 0 :(得分:0)
假设JSON文件位于应用程序包中并且名为cities.json
,则首先创建一个自定义结构City
struct City {
let name : String
let location : CLLocation
}
然后在你的控制器中声明一个数组cities
var cities = [City]()
填充数组反序列化JSON并提取数据
guard let url = NSBundle.mainBundle().URLForResource("cities", withExtension: "json"), jsonData = NSData(contentsOfURL: url) else { return }
do {
let jsonObject = try NSJSONSerialization.JSONObjectWithData(jsonData, options: []) as! [String:AnyObject]
for (cityName, position) in jsonObject {
let coordinates = position["Position"] as! [String:CLLocationDegrees]
let longitude = coordinates["Longitude"]!
let latitude = coordinates["Latitude"]!
let location = CLLocation(latitude: latitude,longitude: longitude)
let city = City(name: cityName, location: location)
cities.append(city)
// print(cities)
}
} catch let error as NSError {
print(error)
}
要查找最近的位置,您可以按距离对数组进行排序
let nearestCity = cities.sort({ userLocation.distanceFromLocation($0.location) < userLocation.distanceFromLocation($1.location) }).first