Swift 4 MapKit检查标记是否在我的位置附近

时间:2018-08-22 13:31:41

标签: swift location mapkit

如果我的位置在马克附近,我想检查一下我的位置何时发生变化。我有独特位置的标记。如果我离标记例如10m,我想显示警报。我该怎么办?

a busy cat

2 个答案:

答案 0 :(得分:0)

You can implement this delegate from CLLocationManager:

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    let myLoc:CLLocationCoordinate2D = manager.location!.coordinate
    let distance : CLLocationDistance = mark1.distanceFromLocation(myLoc)

    if distance < 10.0 { //Show Alert }
}

答案 1 :(得分:0)

  1. 获取可见的注释。
  2. 计算位置与标记之间的距离。

例如

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 }
        }
    }
}