I'm using decoder, And It will show me wrong answer, 1st line is a string, And the second one is I'm converting String to CLLocationCoordinate2D.
Why it makes 1st latitude and last longitude 0.0 ?
Question related to this is : Convert String of CLLocationCoordinate2D(s) into array
My requirement And I want output in this way and store it in 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) ]
Encoding I'm encoding like this way, And encoding is 100% giving correct result.
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
}
Error in decoding
I'm decoding in this way. I'm using this code, It's same like as Convert String of CLLocationCoordinate2D(s) into array But not giving me correct result.
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)
In case your input string look like this:
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
}