使用SwiftUI和MapKit获取用户当前位置

3

我想知道如何使用SwiftUI框架获取用户的当前位置。我已经显示了地图,但我想知道如何获取用户当前位置的纬度和经度。可以自由创建一个类,但请解释一下类的操作以及在哪里实现它。 通过使用UIViewRepresentable和名为makeUIView和updateUIView的两个函数,已经显示了地图。 非常感谢!


参考以下链接获取用户当前位置:https://dev59.com/BVMI5IYBdhLWcg3wUZud 以及创建和组合视图的详细教程:https://developer.apple.com/tutorials/swiftui/creating-and-combining-views#compose-the-detail-view。 - undefined
1个回答

4
创建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
如何创建一个实例? - undefined
你提供的代码加上你给的链接帮了大忙。 - undefined
@Jose 没问题 :) - undefined
另一个问题,当用户移动时,它会保持更新吗? - undefined
显示剩余4条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接