Search code examples
swiftlocationmapkit

Swift 4 MapKit check if mark is near to my location


I want to check when my position is changing if my location is near the Mark. I have marks with unique position. If i near for example 10m from mark i want to display alert. How i can do that?

a busy cat


Solution

    1. Get visible annotations.
    2. Calculate distance between your position and the mark.

    e.g.

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        guard let myLocation = locations.first else { return }
    
        let annotationSet = mapView.annotations(in: mapView.visibleMapRect)
        for annotation in annotationSet {
            guard let annotation = annotation as? MKPointAnnotation else { continue }
            let loc = CLLocation(latitude: annotation.coordinate.latitude,
                                 longitude: annotation.coordinate.longitude)
            let distance = myLocation.distance(from: loc)
            if distance < 10.0 { Show Alert }
            }
        }
    }