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?
CodePudding user response:
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
}
}
CodePudding user response:
Here's what I've tried. Unfortunately I get the error that 'coordinates' is being used before before being initalized:
var trackCoordinates : [CLLocationCoordinate2D] {
var coordinates : [CLLocationCoordinate2D]
for i in 0..<latStrings.count {
if let latitude = Double(latStrings[i]),
let longitude = Double(lonStrings[i]) {
coordinates[i] = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
}
}
return coordinates
}