swift - 将字符串转换为 cllocationcoordinate2d swift 数组

标签 swift

我使用的 API 返回包含坐标的 String。如何转换此响应:

"route_pins": "#30.0539983,30.943465#30.0539033,30.9434167#30.05379,30.9434467#30.0536117,30.943865#30.0535133,30.9439867#30.0534633,30.9440967#30.05353,30.94428#30.053675,30.944525#30.0539933,30.9449667#30.0541517,30.9452317#30.0542917,30.9454717#30.054365,30.9455717#30.0544667,30.945725#30.05471,30.9460733#30.0548667,30.94631#30.0550417,30.9465683#30.0553733,30.9471133#30.0557133,30.9476383#30.0558667,30.947905#30.0560083,30.9481767#30.0562517,30.94872#30.0564917,30.9492217#30.0565783,30.9494567#30.056645,30.9496883#30.0566167,30.9501883"

进入 CLLocationCoordinate2DArray 以使用 MapKit 绘制一条线,使用:

let polyLine = MKPolyline(coordinates: Locations , count: Locations.count)
busMapView.add(polyLine)

最佳答案

您可以结合使用 components(separatedBymap

  • 按字符 # 拆分字符串并删除第一个(空)项。
  • 通过用逗号分隔字符串将每个项目映射到 CLLocationCoordinate2D,将字符串转换为 CLLocationCoordinate2D 并创建坐标。

let routePins = "#30.0539983,30.943465#30.0539033,30.9434167#30.05379,30.9434467#30.0536117,30.943865#30.0535133,30.9439867#30.0534633,30.9440967#30.05353,30.94428#30.053675,30.944525#30.0539933,30.9449667#30.0541517,30.9452317#30.0542917,30.9454717#30.054365,30.9455717#30.0544667,30.945725#30.05471,30.9460733#30.0548667,30.94631#30.0550417,30.9465683#30.0553733,30.9471133#30.0557133,30.9476383#30.0558667,30.947905#30.0560083,30.9481767#30.0562517,30.94872#30.0564917,30.9492217#30.0565783,30.9494567#30.056645,30.9496883#30.0566167,30.9501883"

let coordinates = routePins.components(separatedBy: "#").dropFirst().map { (pin) -> CLLocationCoordinate2D in
    let latLng = pin.components(separatedBy: ",").map{ CLLocationDegrees($0)! }
    return CLLocationCoordinate2D(latitude: latLng[0], longitude: latLng[1])
}

结果是[CLLocationCoordinate2D]

关于swift - 将字符串转换为 cllocationcoordinate2d swift 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51156426/

相关文章:

xcode - 为什么没有设置 Swift 编译器标志?

ios - Interface Builder 中的未知类,从 xcode9 beta5 迁移到 xcode 8.3

ios - 在具有较大 contentSize 的 UIScrollView 中居中 UIImageView

ios - 隐藏导航栏但显示带背景的状态栏

ios - 如何在 Swift 3.0 中使用 Visual 格式设置自动布局约束

ios - 委托(delegate)函数未被调用 iOS Swift

swift/ARKit : Place an object node on a detected surface without touching the screen

ios - swift/图表 : chart value int instead of double

ios - 将重新排序图标设置为透明 UITableViewCells - moverowat 函数

ios - Watch Connectivity 第一次工作但之后就不行了