首页 > 解决方案 > 如何在 IOS Swift 中获取准确的当前位置坐标(纬度/经度)

问题描述

我在 IOS Swift 中使用 CoreLocation 来获取当前坐标,但在某些情况下,它让我最接近我想要的位置,而有时坐标距离我给定的地址有很多米。请检查我正在使用的代码是否有其他方法可以获得准确的当前位置坐标。?

我的代码是:

import CoreLocation

var locationManager:CLLocationManager!
var userLat = 0.0
var userLong = 0.0

override func viewDidLoad() {
    super.viewDidLoad() 

self.locationManager = CLLocationManager()
self.locationManager.delegate = self
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
self.locationManager.requestAlwaysAuthorization()
    
if CLLocationManager.locationServicesEnabled(){
   self.locationManager.startUpdatingLocation()
     }

 }

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: 
 [CLLocation]) {
    
    guard let userLocation :CLLocation = locations.first else{return}
    
    userLat = userLocation.coordinate.latitude
    userLong = userLocation.coordinate.longitude
    
    //current location
    print("current location latitude is :%@", userLat)
    print("current location longitude is :%@", userLong)
        
}

func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
    
    print(Error: \(error)")

}

请帮助我一段时间当前位置是准确的,有时它太远了。谢谢

标签: iosswiftcore-locationcllocationcurrentlocation

解决方案


假设您的应用程序的用户允许您使用精确的位置,您仍然需要考虑这样一个事实,即所提供的位置仅与硬件所能提供的一样准确。定位准确需要时间,并且您可能会didUpdateLocations在系统预热时看到多个呼叫。

您可以使用horizontalAccuracyand verticalAccuracyon aCLLocation来决定如何处理位置更新。


推荐阅读