将CLLocationCoordinate2D转换为一个数组

4

我有多个位置动态地绘制在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)")
    }

以下是在控制台中的打印输出 - 输出结果

我需要输出的打印格式能够正确运行 - 期望的输出结果

希望您能理解我的意思。非常感谢您的帮助!谢谢阅读。


请展示更多的代码,而不仅仅是创建单个坐标的那一行代码。这样无法创建任何类型的数组。 - luk2302
@luk2302:它不会创建单个坐标,正如您可以从保存用户输入的地点在核心数据中作为坐标的输出图像中看到的那样。我已经更新了帖子并添加了更多代码。 - rscode101
1个回答

5
您可以创建一个 CLLocationCoordinate2D 数组:

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)
    }
}

编辑:

在你的代码中,latarraylonarray都不是数组。如果你想创建一个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
    }
}

我现在遇到的问题是每次都为核心数据中的地点数量创建一个数组。该图像显示了这个问题 链接。目前存储了4个位置,最后一个数组在输出中显示。我该如何解决这个问题? - rscode101
愚蠢的错误,我把打印放在循环外面,所以一切都正确显示了!谢谢!我仍然有线绘图的问题,但现在我可以继续前进了。再次感谢。 - rscode101
@rscode101 没问题,只要在SO上得到满意的答案后记得将其标记为已解决。 - xoudini
我遇到了另一个问题,也许你可以帮助我解决。在创建MKPointAnnotion时,如何使用我们刚刚创建的存储数组坐标,因为我得到了这个错误Cannot assign value of type '[CLLocationCoordinate2D]' to type 'CLLocationCoordinate2D' 有什么想法吗?@dzk - rscode101
locations 现在是一个数组,因此您需要从中选择一个对象来分配给每个 MKPointAnnotation,我将更新上面的答案。 - xoudini

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接