简体   繁体   English

使用 SwiftUI 和 MapKit 检索用户当前位置

[英]Retrieve user current location using SwiftUI and MapKit

I would like to know how to get the user current location using SwiftUI Framework.我想知道如何使用 SwiftUI 框架获取用户当前位置。 I have the map displaying already but I want to know how to get the user latitude and longitude of current location.我已经显示了地图,但我想知道如何获取用户当前位置的纬度和经度。 Feel free to create a class but please explain the class actions and where to implement it.随意创建一个类,但请解释类操作以及在何处实现它。 By having the map to display already is by using the UIViewRepresentable and the two functions called makeUIView and updateUIView Thank you in advance通过使用 UIViewRepresentable 和两个名为 makeUIView 和 updateUIView 的函数来显示地图,提前谢谢

Create instance of CLLocationManager :创建CLLocationManager实例:

var locManager = CLLocationManager()
locManager.requestWhenInUseAuthorization()

then get the details:然后获取详细信息:

var currentLocation: CLLocation!

if( CLLocationManager.authorizationStatus() == .authorizedWhenInUse ||
    CLLocationManager.authorizationStatus() ==  .authorizedAlways){

  currentLocation = locManager.location

}

then to get longitude or latitude:然后获取经度或纬度:

let longitude = currentLocation.coordinate.longitude
let latitude = currentLocation.coordinate.latitude

If you'd like to perform it inside a swiftUI view script, create instance:如果您想在 swiftUI 视图脚本中执行它,请创建实例:

@ObservedObject var locationManager = LocationManager()

Get them separately:分别获取它们:

var userLatitude: String {
    return "\(locationManager.lastLocation?.coordinate.latitude ?? 0)"

var userLongitude: String {
        return "\(locationManager.lastLocation?.coordinate.longitude ?? 0)"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM