Search code examples
iosswiftmapkitcore-locationmkcircle

Detect if user stepped out MKCircle | MapKit


Things I need (easier explanation):

  1. [Done] Get users location and show it in UIMapView
  2. [Done] Add Circle around user in UIMapView
  3. Detect if user leaves that circle

This is my code for 1 and 2:

import UIKit 
import MapKit 
import CoreLocation

class ViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate {

    @IBOutlet weak var myMap: MKMapView!

    let manager = CLLocationManager()
    var addedCircle = false


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

        let location = locations[0]

        let span: MKCoordinateSpan = MKCoordinateSpanMake(0.01, 0.01)
        let myLocation: CLLocationCoordinate2D = CLLocationCoordinate2DMake(location.coordinate.latitude,
                                                                        location.coordinate.longitude)
        let region: MKCoordinateRegion = MKCoordinateRegionMake(myLocation, span)

        myMap.setRegion(region, animated: true)



        self.myMap.showsUserLocation = true

        if !addedCircle {
            self.addRadiusCircle(location: location)
            putted = true
        }

    }



    func addRadiusCircle(location: CLLocation){
        self.myMap.delegate = self
        let circle = MKCircle(center: location.coordinate, radius: 100)
        self.myMap.add(circle)
    }

    func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
        if overlay is MKCircle {
            let circle = MKCircleRenderer(overlay: overlay)
            circle.strokeColor = UIColor.red
            circle.fillColor = UIColor(red: 255, green: 0, blue: 0, alpha: 0.1)
            circle.lineWidth = 1
            return circle
        } else {
            return MKPolylineRenderer()
        }
    }


    override func viewDidLoad() {
        super.viewDidLoad()

        manager.delegate = self
        manager.desiredAccuracy = kCLLocationAccuracyBest
        manager.requestWhenInUseAuthorization()
        manager.startUpdatingLocation()

    }


}

And this is the result of this code: enter image description here

That circle doesn't move with the user, and I wanted to know how to detect if user is stepped out of that red circle, thanks in advance for the answer


Solution

  • You can use the distance(from:) method of CLLocation to determine the distance between the user's current location, and the center of the circle.

    let location = CLLocation()
    let circleCenter = CLLocation()
    
    if location.distance(from: circleCenter) > circleRadius {
        // User is outside of circle.
    }