繁体   English   中英

startMonitoringFromRegion-在didEnterRegion中做什么?

[英]startMonitoringFromRegion - what to do in didEnterRegion?

我目前正在实现startMonitoringFromRegion:

-  (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{   
    self.currentLocation = newLocation;


    if (![CLLocationManager regionMonitoringAvailable] ||
        ![CLLocationManager regionMonitoringEnabled])
        return;

    CLLocationDegrees radius = 5;
    if (radius > self.locationManager.maximumRegionMonitoringDistance)
        radius = self.locationManager.maximumRegionMonitoringDistance;


    CLRegion* region = [[CLRegion alloc] initCircularRegionWithCenter:self.currentLocation.coordinate
                                                               radius:radius 
                                                           identifier:@"Indentifier"];

    [self.locationManager startMonitoringForRegion:region desiredAccuracy:kCLLocationAccuracyHundredMeters];
    [region release];

}

当我输入一个新区域时,didEnterRegion将被调用。 我的问题是,在didEnterRegion中应该怎么做?

我有一个所有坐标的数组。 我应该提取region.center并将该坐标与我的坐标数组进行比较,然后查看哪一个最接近region.center?

我注意到CLRegion有一个很棒的方法,称为containsCoordinate。

因此,我现在可以只使用containsCoordinate,而不必遍历didEnterRegion中所有麦当劳的数组坐标并检查它们与region.center的距离是否小于x公里。

for (Restaurant *restaurant in arrRestaurants)
{
    CLLocation *restaurantLocation = [[CLLocation alloc] initWithLatitude:[resturant.latitude doubleValue] longitude:[restraurant.longitude doubleValue]];

    if ([region containsCoordinate: restaurantLocation.coordinate])
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"McDonads found in the region!" message:[NSString stringWithFormat:@"%@", restaurant.town] delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
        [alert show];
        [alert release];         
    }
}

现在,我还没有尝试过,但是对我来说似乎合乎逻辑。

您将需要为CLLocationManager实现-didEnterRegion-didExitRegion方法。 您将根据进入/退出区域所需发生的情况执行代码。

我已经根据您的评论编辑了答案。 如果您需要计算自己与点之间的距离,则可以采用这种方式。

- (CLLocationDistance)distanceFromLocation:(const CLLocation *)location

您可以从region.center创建位置点。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM