我有一个动态数量的位置被绘制到mapkit上。我很好奇如何将当前的纬度和经度变成单个阵列,因为它们当前被打印为单独的对象,而不是像它应该的那样绘制地图。我知道问题,但不知道如何解决它。这是我当前生成坐标的代码 -
do {
let place = try myContext.executeFetchRequest(fetchRequest) as! [Places]
for coords in place{
let latarray = Double(coords.latitude!)
let lonarray = Double(coords.longitude!)
let arraytitles = coords.title!
let destination:CLLocationCoordinate2D = CLLocationCoordinate2DMake(latarray, lonarray)
print(destination)
} catch let error as NSError {
// failure
print("Fetch failed: \(error.localizedDescription)")
}
这是控制台中的打印 - Output
我需要打印件才能正常工作 - Desired output
我希望你理解我的意思。我非常感谢任何帮助!谢谢你的阅读。
答案 0 :(得分:3)
您可以创建CLLocationCoordinate2D
s:
var coordinateArray: [CLLocationCoordinate2D] = []
if latarray.count == lonarray.count {
for var i = 0; i < latarray.count; i++ {
let destination = CLLocationCoordinate2DMake(latarray[i], lonarray[i])
coordinateArray.append(destination)
}
}
修改强>
在您的代码中,latarray
和lonarray
都不是数组。如果你想创建一个CLLocationCoordinate2D
的数组,你应该添加一个变量来存储你的位置,你的for循环应该是这样的:
var locations: [CLLocationCoordinate2D] = []
for coords in place{
let lat = Double(coords.latitude!)
let lon = Double(coords.longitude!)
let title = coords.title!
let destination = CLLocationCoordinate2DMake(lat, lon)
print(destination) // This prints each location separately
if !locations.contains(destination) {
locations.append(destination)
}
}
print(locations) // This prints all locations as an array
// Now you can use your locations anywhere in the scope where you defined the array.
func getLocationFromArray() {
// Loop through the locations array:
for location in locations {
print(location) // Prints each location separately again
}
}