20

我需要检查用户位置是否属于 MKCoordinateRegion。我很惊讶没有找到简单的函数,比如: CGRectContainsCGPoint(rect, point)

我发现了以下一段代码:

CLLocationCoordinate2D topLeftCoordinate = 
    CLLocationCoordinate2DMake(region.center.latitude 
                               + (region.span.latitudeDelta/2.0), 
                               region.center.longitude 
                               - (region.span.longitudeDelta/2.0));


    CLLocationCoordinate2D bottomRightCoordinate = 
    CLLocationCoordinate2DMake(region.center.latitude 
                               - (region.span.latitudeDelta/2.0), 
                               region.center.longitude 
                               + (region.span.longitudeDelta/2.0));

        if (location.latitude < topLeftCoordinate.latitude || location.latitude > bottomRightCoordinate.latitude || location.longitude < bottomRightCoordinate.longitude || location.longitude > bottomRightCoordinate.longitude) {

    // Coordinate fits into the region

    }

但是,我不确定它是否准确,因为文档没有具体说明如何计算区域矩形。

必须有更简单的方法来做到这一点。我是否忽略了 MapKit 框架文档中的某些功能?

4

9 回答 9

20

我发布此答案是因为我认为接受的解决方案无效。这个答案也不完美,但它处理了坐标环绕 360 度边界的情况,这足以适合我的情况。

+ (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;
}
于 2014-05-08T15:35:54.920 回答
16

您可以使用 将您的位置转换为一个点MKMapPointForCoordinate,然后MKMapRectContainsPoint在地图视图的visibleMapRect. 这完全不在我的脑海中。让我知道它是否有效。

于 2012-05-11T14:48:21.187 回答
15

如果有人对纬度和经度感到困惑,这里是经过测试的有效解决方案:

MKCoordinateRegion region = self.mapView.region;

CLLocationCoordinate2D location = user.gpsposition.coordinate;
CLLocationCoordinate2D center   = region.center;
CLLocationCoordinate2D northWestCorner, southEastCorner;

northWestCorner.latitude  = center.latitude  - (region.span.latitudeDelta  / 2.0);
northWestCorner.longitude = center.longitude - (region.span.longitudeDelta / 2.0);
southEastCorner.latitude  = center.latitude  + (region.span.latitudeDelta  / 2.0);
southEastCorner.longitude = center.longitude + (region.span.longitudeDelta / 2.0);

if (
    location.latitude  >= northWestCorner.latitude && 
    location.latitude  <= southEastCorner.latitude &&

    location.longitude >= northWestCorner.longitude && 
    location.longitude <= southEastCorner.longitude
    )
{
    // User location (location) in the region - OK :-)
    NSLog(@"Center (%f, %f) span (%f, %f) user: (%f, %f)| IN!", region.center.latitude, region.center.longitude, region.span.latitudeDelta, region.span.longitudeDelta, location.latitude, location.longitude);

}else {

    // User location (location) out of the region - NOT ok :-(
    NSLog(@"Center (%f, %f) span (%f, %f) user: (%f, %f)| OUT!", region.center.latitude, region.center.longitude, region.span.latitudeDelta, region.span.longitudeDelta, location.latitude, location.longitude);
}
于 2012-05-13T18:51:32.493 回答
7

其他答案都有错误。接受的答案有点冗长,并且在国际日期变更线附近失败。余弦答案是可行的,但对于非常小的区域会失败(因为 delta cosine 是正弦,它趋向于零接近零,这意味着对于较小的角度差异,我们期望零变化)这个答案应该适用于所有情况,并且更简单。

迅速:

/* Standardises and angle to [-180 to 180] degrees */
class func standardAngle(var angle: CLLocationDegrees) -> CLLocationDegrees {
    angle %= 360
    return angle < -180 ? -360 - angle : angle > 180 ? 360 - 180 : angle
}

/* confirms that a region contains a location */
class func regionContains(region: MKCoordinateRegion, location: CLLocation) -> Bool {
    let deltaLat = abs(standardAngle(region.center.latitude - location.coordinate.latitude))
    let deltalong = abs(standardAngle(region.center.longitude - location.coordinate.longitude))
    return region.span.latitudeDelta >= deltaLat && region.span.longitudeDelta >= deltalong
}

目标 C:

/* Standardises and angle to [-180 to 180] degrees */
+ (CLLocationDegrees)standardAngle:(CLLocationDegrees)angle {
    angle %= 360
    return angle < -180 ? -360 - angle : angle > 180 ? 360 - 180 : angle
}

/* confirms that a region contains a location */
+ (BOOL)region:(MKCoordinateRegion*)region containsLocation:(CLLocation*)location {
    CLLocationDegrees deltaLat = fabs(standardAngle(region.center.latitude - location.coordinate.latitude))
    CLLocationDegrees deltalong = fabs(standardAngle(region.center.longitude - location.coordinate.longitude))
    return region.span.latitudeDelta >= deltaLat && region.span.longitudeDelta >= deltalong
}

这种方法虽然对于包含任一极点的区域都失败了,但是坐标系本身在两极处失败了。对于大多数应用程序,此解决方案就足够了。(注意,未在 Objective C 上测试)

于 2014-10-22T09:18:47.610 回答
6

我已经使用此代码来确定坐标是否在圆形区域内(周围有半径的坐标)。

- (BOOL)location:(CLLocation *)location isNearCoordinate:(CLLocationCoordinate2D)coordinate withRadius:(CLLocationDistance)radius
{
    CLCircularRegion *circularRegion = [[CLCircularRegion alloc] initWithCenter:location.coordinate radius:radius identifier:@"radiusCheck"];

    return [circularRegion containsCoordinate:coordinate];
}
于 2014-10-06T12:32:06.993 回答
2

像魅力一样为我工作(Swift 5)

func check(
    location: CLLocationCoordinate2D,
    contains childLocation: CLLocationCoordinate2D,
    with radius: Double)
    -> Bool
{
    let region = CLCircularRegion(center: location, radius: radius, identifier: "SearchId")
    return region.contains(childLocation)
}
于 2020-02-21T18:57:21.530 回答
1

Owen Godfrey,Objective-C 代码不起作用,这是好的代码:在 Objective-C 上失败,这是好的代码:

/* Standardises and angle to [-180 to 180] degrees */
- (CLLocationDegrees)standardAngle:(CLLocationDegrees)angle {
    angle=fmod(angle,360);
    return angle < -180 ? -360 - angle : angle > 180 ? 360 - 180 : angle;
}

-(BOOL)thisRegion:(MKCoordinateRegion)region containsLocation:(CLLocation *)location{
    CLLocationDegrees deltaLat =fabs([self standardAngle:(region.center.latitude-location.coordinate.latitude)]);
    CLLocationDegrees deltaLong =fabs([self standardAngle:(region.center.longitude-location.coordinate.longitude)]);
    return region.span.latitudeDelta >= deltaLat && region.span.longitudeDelta >=deltaLong;
}
    CLLocationDegrees deltalong = fabs(standardAngle(region.center.longitude - location.coordinate.longitude));
    return region.span.latitudeDelta >= deltaLat && region.span.longitudeDelta >= deltalong;
}

谢谢!

于 2015-02-19T10:47:58.637 回答
1

我对相同的计算有问题。我喜欢欧文·戈弗雷(Owen Godfrey)在这里提出的概念,连费尔南多(Fernando)在这里都忽略了纬度与经度包裹不同并且范围不同的事实。为了澄清我的建议,我将其与测试一起发布,以便您自己检查。

import XCTest
import MapKit

// MARK - The Solution

extension CLLocationDegrees {

    enum WrapingDimension: Double {
        case latitude = 180
        case longitude = 360
    }

    /// Standardises and angle to [-180 to 180] or [-90 to 90] degrees
    func wrapped(diemension: WrapingDimension) -> CLLocationDegrees {
        let length = diemension.rawValue
        let halfLenght = length/2.0
        let angle = self.truncatingRemainder(dividingBy: length)
        switch diemension {
        case .longitude:
            //        return angle < -180.0 ? 360.0 + angle : angle > 180.0 ? -360.0 + angle : angle
            return angle < -halfLenght ? length + angle : angle > halfLenght ? -length + angle : angle
        case .latitude:
            //        return angle < -90.0 ? -180.0 - angle : angle > 90.0 ? 180.0 - angle : angle
            return angle < -halfLenght ? -length - angle : angle > halfLenght ? length - angle : angle
        }
    }
}

extension MKCoordinateRegion {
    /// confirms that a region contains a location
    func contains(_ coordinate: CLLocationCoordinate2D) -> Bool {
        let deltaLat = abs((self.center.latitude - coordinate.latitude).wrapped(diemension: .latitude))
        let deltalong = abs((self.center.longitude - coordinate.longitude).wrapped(diemension: .longitude))
        return self.span.latitudeDelta/2.0 >= deltaLat && self.span.longitudeDelta/2.0 >= deltalong
    }
}

// MARK - Unit tests

class MKCoordinateRegionContaingTests: XCTestCase {

    func testRegionContains() {
        var region = MKCoordinateRegionMake(CLLocationCoordinate2DMake(0, 0), MKCoordinateSpan(latitudeDelta: 1, longitudeDelta: 1))
        var coords = CLLocationCoordinate2DMake(0, 0)
        XCTAssert(region.contains(coords))

        coords = CLLocationCoordinate2DMake(0.5, 0.5)
        XCTAssert(region.contains(coords))

        coords = CLLocationCoordinate2DMake(-0.5, 0.5)
        XCTAssert(region.contains(coords))
        coords = CLLocationCoordinate2DMake(0.5, 0.5000001)
        XCTAssert(!region.contains(coords)) // NOT Contains
        coords = CLLocationCoordinate2DMake(0.5, -0.5000001)
        XCTAssert(!region.contains(coords)) // NOT Contains
        coords = CLLocationCoordinate2DMake(1, 1)
        XCTAssert(!region.contains(coords)) // NOT Contains

        region = MKCoordinateRegionMake(CLLocationCoordinate2DMake(0, 180), MKCoordinateSpan(latitudeDelta: 1, longitudeDelta: 1))
        coords = CLLocationCoordinate2DMake(0, 180.5)
        XCTAssert(region.contains(coords))
        coords.longitude = 179.5
        XCTAssert(region.contains(coords))
        coords.longitude = 180.5000001
        XCTAssert(!region.contains(coords)) // NOT Contains
        coords.longitude = 179.5000001
        XCTAssert(region.contains(coords))
        coords.longitude = 179.4999999
        XCTAssert(!region.contains(coords)) // NOT Contains

        region = MKCoordinateRegionMake(CLLocationCoordinate2DMake(90, -180), MKCoordinateSpan(latitudeDelta: 1, longitudeDelta: 1))
        coords = CLLocationCoordinate2DMake(90.5, -180.5)
        XCTAssert(region.contains(coords))

        coords = CLLocationCoordinate2DMake(89.5, -180.5)
        XCTAssert(region.contains(coords))

        coords = CLLocationCoordinate2DMake(90.50000001, -180.5)
        XCTAssert(!region.contains(coords)) // NOT Contains

        coords = CLLocationCoordinate2DMake(89.50000001, -180.5)
        XCTAssert(region.contains(coords))

        coords = CLLocationCoordinate2DMake(89.49999999, -180.5)
        XCTAssert(!region.contains(coords)) // NOT Contains
    }

    func testStandardAngle() {
        var angle = 180.5.wrapped(diemension: .longitude)
        var required = -179.5
        XCTAssert(self.areAngleEqual(angle, required))

        angle = 360.5.wrapped(diemension: .longitude)
        required = 0.5
        XCTAssert(self.areAngleEqual(angle, required))

        angle = 359.5.wrapped(diemension: .longitude)
        required = -0.5
        XCTAssert(self.areAngleEqual(angle, required))

        angle = 179.5.wrapped(diemension: .longitude)
        required = 179.5
        XCTAssert(self.areAngleEqual(angle, required))

        angle = 90.5.wrapped(diemension: .latitude)
        required = 89.5
        XCTAssert(self.areAngleEqual(angle, required))

        angle = 90.5000001.wrapped(diemension: .latitude)
        required = 89.4999999
        XCTAssert(self.areAngleEqual(angle, required))

        angle = -90.5.wrapped(diemension: .latitude)
        required = -89.5
        XCTAssert(self.areAngleEqual(angle, required))

        angle = -90.5000001.wrapped(diemension: .latitude)
        required = -89.4999999
        XCTAssert(self.areAngleEqual(angle, required))
    }

    /// compare doubles with presition to 8 digits after the decimal point
    func areAngleEqual(_ a:Double, _ b:Double) -> Bool {
        let presition = 0.00000001
        let equal = Int(a / presition) == Int(b / presition)
        print(String(format:"%14.9f %@ %14.9f", a, equal ? "==" : "!=", b) )
        return equal
    }
}
于 2018-02-01T14:32:00.157 回答
0

基于 Lukasz 解决方案,但在 Swift 中,以防任何人都可以使用 Swift:

func isInRegion (region : MKCoordinateRegion, coordinate : CLLocationCoordinate2D) -> Bool {

    let center   = region.center;
    let northWestCorner = CLLocationCoordinate2D(latitude: center.latitude  - (region.span.latitudeDelta  / 2.0), longitude: center.longitude - (region.span.longitudeDelta / 2.0))
    let southEastCorner = CLLocationCoordinate2D(latitude: center.latitude  + (region.span.latitudeDelta  / 2.0), longitude: center.longitude + (region.span.longitudeDelta / 2.0))

    return (
        coordinate.latitude  >= northWestCorner.latitude &&
        coordinate.latitude  <= southEastCorner.latitude &&

        coordinate.longitude >= northWestCorner.longitude &&
        coordinate.longitude <= southEastCorner.longitude
    )
}
于 2016-03-23T21:20:23.057 回答