didUpdateLocations
被多次调用。所以我该如何处理停止这个。我尝试在 didUpdateLocations
中使用 locationManager.stopUpdatingLocation()
但它无法正常工作。
override func viewDidLoad()
{
super.viewDidLoad()
//for Authorisation from the User.
isAuthorizedtoGetUserLocation()
if CLLocationManager.locationServicesEnabled() {
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.startUpdatingLocation()
}
}
func isAuthorizedtoGetUserLocation() {
if CLLocationManager.authorizationStatus() != .authorizedWhenInUse {
locationManager.requestWhenInUseAuthorization()
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
locationManager.stopUpdatingLocation()
let locValue:CLLocationCoordinate2D = manager.location!.coordinate
print("locations = \(locValue.latitude) \(locValue.longitude)")
let camera = GMSCameraPosition.camera(withLatitude: locValue.latitude, longitude: locValue.longitude, zoom: 6.0)
let mapView = GMSMapView.map(withFrame: CGRect.zero, camera: camera)
self.view = mapView
// Creates a marker in the center of the map.
let marker = GMSMarker()
marker.position = CLLocationCoordinate2D(latitude: locValue.latitude, longitude: locValue.longitude)
marker.title = "name"
marker.map = mapView
}
有错误的更新代码
func locationManager( _ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
manager.stopUpdatingLocation()
manager = nil // Here it is giving error "Cannot assign to value: 'manager' is a 'let' constant"
var newLocation: CLLocation? = locations.last
var locationAge: TimeInterval? = -(newLocation?.timestamp.timeIntervalSinceNow)!
if Double(locationAge!) > 5.0 {
return
}
if Double((newLocation?.horizontalAccuracy)!) < 0 {
return
}
//manager = nil
let locValue:CLLocationCoordinate2D = manager.location!.coordinate
print("locations = \(locValue.latitude) \(locValue.longitude)")
let camera = GMSCameraPosition.camera(withLatitude: locValue.latitude, longitude: locValue.longitude, zoom: 6.0)
let mapView = GMSMapView.map(withFrame: CGRect.zero, camera: camera)
self.view = mapView
// Creates a marker in the center of the map.
let marker = GMSMarker()
marker.position = CLLocationCoordinate2D(latitude: locValue.latitude, longitude: locValue.longitude)
marker.title = "name"
marker.map = mapView
}
最佳答案
您需要如下设置 CLLocation 管理器的 distanceFilter 属性:
/* Notify changes when device has moved x meters.
* Default value is kCLDistanceFilterNone: all movements are reported.
*/
self.locationManager.distanceFilter = 10.0f; // you can change as per your require ment
关于ios - CLLocationManager didUpdateLocations 被多次调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42593008/