Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if user's current location is inside a location circle

i want to check if user if inside a vicinity. For example i have specified a radius of 50 meters around current of location of user. Let's say if user is moving, now i want to check if user in inside 50 meter radius or not. Here is my code

 override func viewDidLoad() {
        super.viewDidLoad()

          locationManager.startMonitoringVisits()
          locationManager.delegate = self
          locationManager.distanceFilter = 1
          locationManager.allowsBackgroundLocationUpdates = true
          locationManager.startUpdatingLocation() 
    }


Here is code for checking distance


    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

        guard let location = locations.first else {
            return
        }
        let officeLocation = CLLocationCoordinate2D.init(latitude: 31.471303736482234, longitude: 74.27275174139386)

        let circle = MKCircle(center: officeLocation, radius: 50 as CLLocationDistance)
        if location.distance(from: officeLocation) > circle.radius {
            self.newVisitReceived(des: "YOU ARE OUT OF OFFICE")
        }
        else{ 
            self.newVisitReceived(des: "YOU ARE IN OFFICE")
         }

    }

Even if i don't move this code sends notification "YOU ARE OUT".

like image 596
Asad jee Avatar asked Oct 30 '25 02:10

Asad jee


1 Answers

I would solve this with Geofences... You have to specify a coordinate center & radius where you want to listen to the user when he goes inside/outside from your geofence.

override func viewDidLoad() {
    super.viewDidLoad()

    let locationManager = CLLocationManager()
    locationManager.delegate = self
    locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation
    locationManager.allowsBackgroundLocationUpdates = true
    locationManager.requestAlwaysAuthorization()
}

func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
    if status == .authorizedAlways || status == .authorizedWhenInUse {

        // CLLocationCoordinate2D; You have to put the coordinate that you want to listen
        let region = CLCircularRegion(center: CLLocationCoordinate2D(latitude: 324234, longitude: 23423), radius: 50, identifier: "Ur ID")
        region.notifyOnExit = true
        region.notifyOnEntry = true
        manager.startMonitoring(for: region)
    }
}

func locationManager(_ manager: CLLocationManager, didExitRegion region: CLRegion) {
    // User has exited from ur regiom
}

func locationManager(_ manager: CLLocationManager, didEnterRegion region: CLRegion) {
    // User has exited from ur region
}

I hope this will be useful

like image 183
Gabs Avatar answered Oct 31 '25 16:10

Gabs