Reputation: 45
I am trying to see whenever the user's location has been updated. I tried many different listeners, but I can't seem to figure this out. What would be the most effective and efficient way to test whether the user's location has been updated?
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let location = locations[0]
let lat = location.coordinate.latitude
let long = location.coordinate.longitude
print(lat, long)
let currentLocation = CLLocationCoordinate2DMake(lat, long)
let lastLocation = CLLocationCoordinate2DMake((locations.last?.coordinate.latitude)!, (locations.last?.coordinate.longitude)!)
let camera = GMSCameraPosition.camera(withLatitude: lat, longitude: long, zoom: 15)
self.mapView.animate(to: camera)
let geocoder = GMSGeocoder()
if currentLocation.latitude != lastLocation.latitude || currentLocation.longitude != lastLocation.longitude {
let alertController = UIAlertController(title: "Location Update", message: "Current location has been updated", preferredStyle: .alert)
let defaultAction = UIAlertAction(title: "OK", style: .cancel, handler: nil)
alertController.addAction(defaultAction)
self.present(alertController, animated: true, completion: nil)
} else {
print("no update change")
}
geocoder.reverseGeocodeCoordinate(currentLocation) { (response, error) in
if let address = response?.firstResult() {
let lines = address.lines!
self.currentLocationLabel.text = lines.joined(separator: "\n")
}
}
// self.manager.stopUpdatingLocation()
}
Upvotes: 0
Views: 341
Reputation: 321
i think you just wanna get the user's location on the map right? you can get the user's location from the mapview and you can do this in didUpdateLocation
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if let mylocation = mapview.myLocation{
//animate the mapview to user's location
let lat = mylocation.coordinate.latitude
let long = mylocation.coordinate.longitude
let camera = GMSCameraPosition.camera(withLatitude: lat, longitude: long, zoom: 14.0)
mapview.camera = camera
mapview.animate(to: camera)
}
}
Hope it helps.
Upvotes: 1