如何修复“从字符串转换为 CLLocationCoordinate2D 时”。

How to fix 'When converting from string to CLLocationCoordinate2D."

我正在使用解码器,它会显示错误的答案,第一行是一个字符串,第二行是我正在将字符串转换为 CLLocationCoordinate2D。

为什么第一纬度和最后经度为 0.0?

与此相关的问题是:

我的要求 我想以这种方式输出并将其存储在 let coordinates.

let coordinates = [
(-122.63748, 45.52214),
(-122.64855, 45.52218),
(-122.6545, 45.52219),
(-122.65497, 45.52196),
(-122.65631, 45.52104),
(-122.6578, 45.51935),
(-122.65867, 45.51848),
(-122.65872, 45.51293) ]

编码 我是这样编码的,并且编码是 100% 给出正确的结果。

 func encodeCoordinates(coords: [CLLocationCoordinate2D]) -> String {
//        let flattenedCoords: [String] = coords.map { coord -> String in "\(coord.latitude):\(coord.longitude)" }
        let flattenedCoords: [String] = coords.map { coord -> String in "\(coord.latitude):\(coord.longitude)"}
        let encodedString: String = flattenedCoords.joined(separator: ",")
        print("[\(encodedString)]")
        return encodedString
    }

它的输出是:

解码错误

我是这样解码的。我正在使用这段代码,它与 一样,但没有给我正确的结果。

func decodeCoordinates(encodedString: String) -> [CLLocationCoordinate2D] {
    let flattenedCoords: [String] = encodedString.components(separatedBy: ",")
    let coords: [CLLocationCoordinate2D] = flattenedCoords.map { coord -> CLLocationCoordinate2D in
        let split = coord.components(separatedBy: ":")
        if split.count == 2 {
            let latitude: Double = Double(split[0]) ?? 0.0
            let longitude: Double = Double(split[1]) ?? 0.0
            return CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
        } else {
            return CLLocationCoordinate2D()
        }
    }
    return coords
}

func makingRouteOfFreeRide(){

print("\n\n\n\n\n\n\n\n oooooo \(ProfileRoutesVC.map)\n\n\n\n\n\n\n\n\n",decodeCoordinates(encodedString: ProfileRoutesVC.map))
let a = decodeCoordinates(encodedString: ProfileRoutesVC.map)

如果您的输入字符串如下所示:

let yourCoordinateString = "[32.4945:74.5229,32.4945:74.5229,32.4945:74.5229]"
func decodeCoordinates(encodedString: String) -> [CLLocationCoordinate2D] {
    var tmpString = encodedString
    tmpString.removeFirst(1)
    tmpString.removeLast(1)

    let flattenedCoords: [String] = tmpString.components(separatedBy: ",")
    let coords: [CLLocationCoordinate2D] = flattenedCoords.map { coord -> CLLocationCoordinate2D in
        let split = coord.components(separatedBy: ":")
        if split.count == 2 {
            let latitude: Double = Double(split[0]) ?? 0.0
            let longitude: Double = Double(split[1]) ?? 0.0
                return CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
            } else {
                return CLLocationCoordinate2D()
            }
        }

        return coords
}