如何检测当前位置是否位于具有CoreLocation的区域内

问题描述 投票:2回答:2

我希望我的应用程序知道用户是否在特定区域内。我一直在学习地理围栏,但我不希望设备不断检查它是否正在进入或离开某个区域,我只是想知道它是否在那个具体时刻就在它上面。另外,我读到地理围栏已经(似乎)精度很低,而且我需要的不仅仅是蜂窝塔精度。 所以我的想法是使用“标准”类型的位置来做到这一点,但我不知道如何在给定新的当前位置的情况下检查它是否在(圆形,矩形,多边形?)区域内。 它可能必须使用纯数学来检查,检查高度是否在2个参数之间,对经度是否如此?有更简单的方法吗?

谢谢!

objective-c geolocation core-location region
2个回答

1
投票

这是我对Jordan Curve定理的Swift代码。只需提供一系列CLLocationCoordinate2D,它可以制作正方形,多边形,任何东西。

更深入的答案我翻译了这个:How can I determine whether a 2D Point is within a Polygon?

原网站:PNPOLY - Point Inclusion in Polygon Test W. Randolph Franklin (WRF)

extension CLLocationCoordinate2D {

    func liesInsideRegion(region:[CLLocationCoordinate2D]) -> Bool {

        var liesInside = false
        var i = 0
        var j = region.count-1

        while i < region.count {

            guard let iCoordinate = region[safe:i] else {break}
            guard let jCoordinate = region[safe:j] else {break}

            if (iCoordinate.latitude > self.latitude) != (jCoordinate.latitude > self.latitude) {
                if self.longitude < (iCoordinate.longitude - jCoordinate.longitude) * (self.latitude - iCoordinate.latitude) / (jCoordinate.latitude-iCoordinate.latitude) + iCoordinate.longitude {
                    liesInside = !liesInside
                    }
            }

            i += 1
            j = i+1
        }

        return liesInside
    }

}

编辑

安全数组项目

extension MutableCollection {
    subscript (safe index: Index) -> Iterator.Element? {
        get {
            guard startIndex <= index && index < endIndex else { return nil }
            return self[index]
        }
        set(newValue) {
            guard startIndex <= index && index < endIndex else { print("Index out of range."); return }
            guard let newValue = newValue else { print("Cannot remove out of bounds items"); return }
            self[index] = newValue
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.