如何解决“当从字符串转换为CLLocationCoordinate2D时。”

时间:2019-10-17 19:19:22

标签: ios swift cllocationcoordinate2d

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

enter image description here

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

与此相关的问题是:Convert String of CLLocationCoordinate2D(s) into array

我的要求 我希望以这种方式输出并将其存储在 let坐标中。

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
    }

其输出为: enter image description here

解码错误

我正在以这种方式解码。我正在使用此代码,它与Convert String of CLLocationCoordinate2D(s) into array一样,但是没有给我正确的结果。

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)

enter image description here

1 个答案:

答案 0 :(得分:1)

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

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
}