在 iOS swiftui 视图中实现正向地理编码功能

Implementing forward geocoding function inside an iOS swiftui view

所以我正在尝试使用 swiftui 制作一个 iOS 应用程序,它转发对地址进行地理编码,然后将这些坐标放置在可以在我的其余视图中使用的变量中。我用于正向地理编码的函数如下所示:

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()
    }
}

我的问题是,我应该如何在我的 contentview 文件中调用这个函数,以便我可以将坐标保存为变量,以及我如何调用该函数将它们打印到屏幕上,以验证代码是否正确运行.

您可以在 onAppear() 方法中以非常简单的方式这样做。但是,我鼓励您使用视图模型来使用地址获取坐标。

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)
        }
    }
}