I have an error issue that I haven’t been able to solve despite doing extensive research. In fact the similar examples I have found so far have been educational but I have not been able to make work. The example below I am hoping will be easy to fix as it is only producing errors with one line of code…
import SwiftUI
import CoreLocation
var currentLon = Double()
var currentLat = Double()
extension CLLocation {
class func distance(from: CLLocationCoordinate2D, to: CLLocationCoordinate2D) -> CLLocationDistance {
let from = CLLocation(latitude: from.latitude, longitude: from.longitude)
let to = CLLocation(latitude: to.latitude, longitude: to.longitude)
return from.distance(from: to)
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
currentLon = (locations.last?.coordinate.longitude)!
currentLat = (locations.last?.coordinate.latitude)!
}/*⚠️ Not sure if this function will work? (Update User Location coordinates on the move?)*/
}
struct Positions: Identifiable {
let id = UUID()
let name: String
let latitude: Double
let longitude: Double
var coordinate: CLLocationCoordinate2D {
CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
}
}
struct GameMapView: View {
let from = CLLocationCoordinate2D(latitude: currentLon, longitude: currentLat)
let to = CLLocationCoordinate2D(latitude: thisCardPositionLongitude, longitude: thisCardPositionLongitude)
let distanceFrom = from.distance(from: to)
/*⚠️ ERRORS:
1. Cannot use instance member 'from' within property initializer; property initializers run before 'self' is available.
2. Cannot use instance member 'to' within property initializer; property initializers run before 'self' is available.
3. Value of type 'CLLocationCoordinate2D' has no member 'distance'. */
@State private var region = MKCoordinateRegion(
center: CLLocationCoordinate2D(
latitude: thisCardPositionLatitude,
longitude: thisCardPositionLongitude),
span: MKCoordinateSpan(
latitudeDelta: 0.0001,
longitudeDelta: 0.0001)
)
var body: some View {
Map(coordinateRegion: $region,
showsUserLocation: true,
annotationItems: locations){ place in
MapMarker(coordinate: place.coordinate,tint: Color.accentColor)
}
.edgesIgnoringSafeArea(.all)
VStack {
Print("Distance from Location: \(distanceFrom)")
font(.largeTitle)
padding()
}
You should either declare from and to in:
- an init() - just declare type in the general declaration and set value in init
- in .onAppear as a modifier of the VStack
But there are many errors in the code that you have to correct first:
- you call distance in the distance func. That will cause infinite loop
return from.distance(from: to)
- You need to set values of parameters,
let distanceFrom = from.distance(from: to)
- such as
let distanceFrom = from.distance(from: from, to: to)
- from is a CLLocationCoordinate2D
But distance is defined for CLLocation only…