カテゴリー
iOS Swift

任意の点がMKCoordinateRegion内にあるかを調べるには

任意の点CLLocationCoordinate2DがMapViewのMKCoordinateRegionの中にあるのかを知る方法を調べていたら、このStackOverflowの投稿に辿りつきました。

+ (BOOL)coordinate:(CLLocationCoordinate2D)coord inRegion:(MKCoordinateRegion)region
{
    CLLocationCoordinate2D center = region.center;
    MKCoordinateSpan span = region.span;

    BOOL result = YES;
    result &= cos((center.latitude - coord.latitude)*M_PI/180.0) > cos(span.latitudeDelta/2.0*M_PI/180.0);
    result &= cos((center.longitude - coord.longitude)*M_PI/180.0) > cos(span.longitudeDelta/2.0*M_PI/180.0);
    return result;
}

Swiftで書くとこのようになると思います。

func checkIfCoordinateInRegion(coordinate: CLLocationCoordinate2D, region: MKCoordinateRegion) -> Bool {
        let center = region.center
        let span = region.span
        return cos((center.latitude - coordinate.latitude)*Double.pi/180.0) > cos(span.latitudeDelta/2.0*Double.pi/180.0) && cos((center.longitude - coordinate.longitude)*Double.pi/180.0) > cos(span.longitudeDelta/2.0*Double.pi/180.0)
}

なぜcosで計算すると良いのかがパッと見分からなかったので考えてみました。

まず、地球を描きます。

The Earth
Draw imaginary latitude and longtitude.

Draw an imaginary span area
Viewing the earth from the side.
Here is cosθ of your span area.
If a point is inside the span area, its cosθ’ will always be greater than cosθ.