Reputation: 109
So I'm trying to make an iOS app using swiftui that forward geocodes an address and then places those coordinates in variables that can be used in the rest of my views. The function I'm using for forward geocoding looks like this:
import SwiftUI
import CoreLocation
struct ContentView: View {
@State var myText = "Some Text just for reference"
@State var location: CLLocationCoordinate2D?
@State var lat: Double?
@State var long: Double?
var body: some View {
VStack{
Text(myText)
.onAppear {
self.getLocation(from: "22 Sunset Ave, East Quogue, NY") { coordinates in
print(coordinates ?? 0) // Print here
self.location = coordinates // Assign to a local variable for further processing
self.long = coordinates?.longitude
self.lat = coordinates?.latitude
}
}
Text("\(long)")
Text("\(lat)")
}
}
func getLocation(from address: String, completion: @escaping (_ location: CLLocationCoordinate2D?)-> Void) {
let geocoder = CLGeocoder()
geocoder.geocodeAddressString(address) { (placemarks, error) in
guard let placemarks = placemarks,
let location = placemarks.first?.location?.coordinate else {
completion(nil)
return
}
completion(location)
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
My questions are, how should I be calling this function inside of my contentview file so I can save the coordinates as variables and how do I call the function to print them to the screen just to verify the code is operating correctly.
Upvotes: 0
Views: 1708
Reputation: 705
You can do it like this within the onAppear()
method in a very simple manner. However, I would encourage you to use a View Model to fetch the coordinates using an address.
struct ContentView: View {
@State var myText = "Some Text just for reference"
@State var location: CLLocationCoordinate2D?
var body: some View {
Text(myText)
.onAppear {
self.getLocation(from: "Some Address") { coordinates in
print(coordinates) // Print here
self.location = coordinates // Assign to a local variable for further processing
}
}
}
func getLocation(from address: String, completion: @escaping (_ location: CLLocationCoordinate2D?)-> Void) {
let geocoder = CLGeocoder()
geocoder.geocodeAddressString(address) { (placemarks, error) in
guard let placemarks = placemarks,
let location = placemarks.first?.location?.coordinate else {
completion(nil)
return
}
completion(location)
}
}
}
Upvotes: 1