(Swift)在我的位置MapKit

时间:2017-05-23 00:15:00

标签: ios swift mapkit

我正在使用App获取用户位置以及我添加的一些自定义引脚(餐馆)。我想要做的是设置用户和餐馆之间的半径(在5公里到10公里之间),然后显示该区域内的那些。

我的问题是,如何设置该半径并获取其中的位置

祝你好运!

1 个答案:

答案 0 :(得分:2)

您可以进行一些距离计算以确定要显示的引脚。

let pins = Array<MKPointAnnotation>() // This is an empty array, so just use your array of locations or add to this.

if let currentLocation = locationManager.location?.coordinate {

    for pin in pins {

        let locationMapPoint = MKMapPointForCoordinate(currentLocation)

        let pinMapPoint = MKMapPointForCoordinate(pin.coordinate)

        let distance = MKMetersBetweenMapPoints(locationMapPoint, pinMapPoint)

        if distance >= 5000 && distance <= 10000 {

            self.map.addAnnotation(pin)
        }
    }
}

如果你想要更整洁的东西,你也可以这样做。

let pins = Array<MKPointAnnotation>()

if let currentLocation = locationManager.location?.coordinate {

    let filtered = pins.filter { $0.coordinate.distance(to: currentLocation) >= 5000 && $0.coordinate.distance(to: currentLocation) <= 10000 }

    self.map.addAnnotations(filtered)
}

你也需要这个扩展。

extension CLLocationCoordinate2D {

    func distance(to coordinate: CLLocationCoordinate2D) -> Double {

        return MKMetersBetweenMapPoints(MKMapPointForCoordinate(self), MKMapPointForCoordinate(coordinate))
    }
}