开发者

startMonitoringFromRegion - what to do in didEnterRegion?

I'm currently implementing 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
                         开发者_StackOverflow中文版                                      radius:radius 
                                                           identifier:@"Indentifier"];

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

}

When I enter a new region didEnterRegion will get called. My question here is, what should I do in didEnterRegion?

I have an array of all my coordinates. Should I extract region.center and compare that coordinate to my array of coordinates, and see which one of the coordinates that's closest to region.center?


I noted that CLRegion has a wonderful method called containsCoordinate.

So instead of looping through all my McDonald's array coordinates in didEnterRegion and check if their distance is less than x kilometers from region.center, I can now just use containsCoordinate.

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];         
    }
}

Now, I haven't tried this yet, but to me it seems logical.


You will need to implement the -didEnterRegion and -didExitRegion methods for your CLLocationManager. You would execute your code based on what you need to happen for entering/exiting the region.

I have edited my answer based on your comment. If you need to calculate the distance between you and your point, you can do it this way.

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

You could create your location point from region.center.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜