我想知道如何使用SwiftUI框架获取用户的当前位置。我已经显示了地图,但我想知道如何获取用户当前位置的纬度和经度。可以自由创建一个类,但请解释一下类的操作以及在哪里实现它。 通过使用UIViewRepresentable和名为makeUIView和updateUIView的两个函数,已经显示了地图。 非常感谢!
我想知道如何使用SwiftUI框架获取用户的当前位置。我已经显示了地图,但我想知道如何获取用户当前位置的纬度和经度。可以自由创建一个类,但请解释一下类的操作以及在哪里实现它。 通过使用UIViewRepresentable和名为makeUIView和updateUIView的两个函数,已经显示了地图。 非常感谢!
CLLocationManager
实例:var locManager = CLLocationManager()
locManager.requestWhenInUseAuthorization()
然后获取详细信息:
var currentLocation: CLLocation!
if( CLLocationManager.authorizationStatus() == .authorizedWhenInUse ||
CLLocationManager.authorizationStatus() == .authorizedAlways){
currentLocation = locManager.location
}
获取经度或纬度:
let longitude = currentLocation.coordinate.longitude
let latitude = currentLocation.coordinate.latitude
如果您想在SwiftUI视图脚本中执行它,请创建实例:
@ObservedObject var locationManager = LocationManager()
分别获取它们:
var userLatitude: String {
return "\(locationManager.lastLocation?.coordinate.latitude ?? 0)"
var userLongitude: String {
return "\(locationManager.lastLocation?.coordinate.longitude ?? 0)"
print("纬度:\(userLatitude) 经度:\(userLongitude)")
。 - undefined