I have two strings that represent latitude and longitude Data of a route. In total they have around 900 entries each. I'd like to convert them to CLLocation Coordinates and then use these Coordinates to create the route as a Map polyline-overlay in a different view.

So. I'm especially interested in two issues:

  • convert the strings into coordinates
  • make the coordinates accessible by different views (maybe EnvironmentObject?)

For the conversion I tried this so far:

import SwiftUI
import Foundation
import CoreLocation
import MapKit

struct TrackData2: View {

let track01_lat = "29.0228176937071,29.022820134536,29.0228225788423"

let track01_long = "4.43144629937264,4.43144455316597,4.43144281824249"

var body: some View {
    var lat = track01_lat.components(separatedBy: ",")
    var long = track01_long.components(separatedBy: ",")

    let latitude = Double(lat)
    let longitude = Double(long)

    let coordinate:CLLocation = CLLocation(latitude: latitude, longitude: longitude)
}
}

But I get an error for Double(): "No exact matches in call to initializer". Any tipps on that?

1

There are 1 best solutions below

2
malhal On

You've got an array of numbers as strings so you have to do:

    let latStrings = track01_lat.components(separatedBy: ",")
    let lonStrings = track01_long.components(separatedBy: ",")
    
    if latStrings.count != lonStrings.count {
        // counts don't match
    }
    
    for i in 0..<latStrings.count {
        if let latitude = Double(latStrings[i]),
            let longitude = Double(lonStrings[i]) {
            let coordinate = CLLocation(latitude: latitude, longitude: longitude)
            
            // use the coordinate
        }
    }