因此,我尝试制作一个程序来检索用户的位置,这一次我想获取该区域中的纬度和经度,但是如何检索它们并将它们存储在一个变量中
import SwiftUI
import MapKit
import CoreLocationUI
struct ContentView: View {
@StateObject private var viewModel = ContentViewModel()
@State var LongStorage : Int = 0
@State var LangStorage : Int = 0
var body: some View {
ZStack(alignment: .bottom){
Map(coordinateRegion: $viewModel.region, showsUserLocation: true)
.ignoresSafeArea()
.tint(Color("GreenColor"))
LocationButton(.currentLocation){
viewModel.requestAllowOnceLocationPermission()
}
.foregroundColor(.white )
.cornerRadius(10)
.labelStyle(.titleAndIcon)
.symbolVariant(.fill)
.tint(Color("GreenColor"))
.padding(.bottom, 50)
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
final class ContentViewModel: NSObject, ObservableObject, CLLocationManagerDelegate{
@Published var region = MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: 40, longitude: 120), span: MKCoordinateSpan(latitudeDelta: 100, longitudeDelta: 100))
let locationManager = CLLocationManager()
override init() {
super.init()
locationManager.delegate = self
}
func requestAllowOnceLocationPermission() {
locationManager.requestLocation()
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let latestLocation = locations.first else{
//Show an error
return
}
DispatchQueue.main.async {
self.region = MKCoordinateRegion(center: latestLocation.coordinate, span: MKCoordinateSpan(latitudeDelta: 0.015, longitudeDelta: 0.015))
//check region value
print("Region --> \(self.region)")
}
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print(error.localizedDescription)
}
}这就是终点站的结果,我怎么才能得到经纬度?
Region --> MKCoordinateRegion(center: __C.CLLocationCoordinate2D(latitude: 37.33036067, longitude: -122.02845007), span: __C.MKCoordinateSpan(latitudeDelta: 0.015, longitudeDelta: 0.015))发布于 2022-07-05 08:38:29
您已经获得了最新位置的值,所以只需将它们赋值给变量:
var latitude = region.center.latitude
var logitude = region.center.longitude对我来说很难测试,因为不能只是复制粘贴您的代码来尝试它。
https://stackoverflow.com/questions/72866019
复制相似问题