2

我有一个 CLLocation 点(纬度/经度),我想知道它是否在确定的 MKCoordinateRegion 中。我想知道之前在哪个区域创建了 CLLocation 点。

谢谢。

我找到了解决方案。

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);
}
4

2 回答 2

1

有类似的问题。回答正确 -如何在不使用 MKMapView 的情况下检查 MKCoordinateRegion 是否包含 CLLocationCoordinate2D?

祝你好运 :)

于 2013-02-17T00:47:38.210 回答
0

这似乎是正确的,但倒退了。区域西北角的纬度将大于中心,因为随着您向北移动,纬度会增加。经度是正确的。所以这里计算的角是交换的,northwestCorner实际上是西南角,seasternCorner实际上是东北角。但是代码有效,因为 if 语句也是向后的。它应该更像

CLLocationCoordinate2D newMapCenter = self.mapView.centerCoordinate;
CLLocationCoordinate2D startingCenter = self.startingRegion.center;
CLLocationCoordinate2D northWestCorner, southEastCorner;

northWestCorner.latitude = startingCenter.latitude + (self.startingRegion.span.latitudeDelta / 2.0);
northWestCorner.longitude = startingCenter.longitude - (self.startingRegion.span.longitudeDelta / 2.0);
southEastCorner.latitude = startingCenter.latitude - (self.startingRegion.span.latitudeDelta / 2.0);
southEastCorner.longitude = startingCenter.longitude + (self.startingRegion.span.longitudeDelta / 2.0);

if (newMapCenter.latitude <= northWestCorner.latitude && newMapCenter.latitude >= southEastCorner.latitude && newMapCenter.longitude >= northWestCorner.longitude && newMapCenter.longitude <= southEastCorner.longitude) {
    // still in original region
    NSLog(@"same region");
}
else
{
    // new region
    NSLog(@"new region");
}

所以答案是对的,但也是错的。但它有效,所以我想它更正确。

于 2014-01-31T17:04:53.707 回答