检测用户是否走出MKCircle | MapKit

时间:2017-12-25 18:51:54

标签: ios swift mapkit core-location mkcircle

我需要的东西(更容易解释):

  1. [完成] 获取用户位置并在UIMapView中显示
  2. [完成] 在UIMapView中为用户添加圈子
  3. 检测用户是否离开该圈
  4. 这是我的1和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()
    
        }
    
    
    }
    

    这是此代码的结果: enter image description here

    该圈子不会随着用户移动,我想知道如何检测用户是否已离开该红圈,提前感谢答案

1 个答案:

答案 0 :(得分:2)

您可以使用distance(from:) CLLocation方法来确定用户当前位置与圈子中心之间的距离。

let location = CLLocation()
let circleCenter = CLLocation()

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