Tanner Quigley
Tanner Quigley

Reputation: 246

Checking Proximity of two Locations in IOS

I have an array of locations and when I add another I want to be able to check if the other locations in the array are within a block of the new one. This is the Code I have to find the current location:

//Geocoding Block
[self.geoCoder reverseGeocodeLocation: locationManager.location completionHandler:
 ^(NSArray *placemarks, NSError *error) {

     //Get nearby address
     CLPlacemark *placemark = [placemarks objectAtIndex:0];

     //String to hold address
    locatedAt = [[placemark.addressDictionary valueForKey:@"FormattedAddressLines"]    componentsJoinedByString:@", "];

The array has yet to be created because I want to figure this out first, I dont know what should be held in the array (string...). I know how to do a search I just need to know how to compare the locations.

Upvotes: 3

Views: 845

Answers (1)

bdesham
bdesham

Reputation: 16089

You can get the distance between two locations using the distanceFromLocation: method on CLLocation. (You can get a CLLocation out of a CLPlacemark with myPlacemark.location.) So if you have an array of CLLocation objects, and you want to find the ones that are within one block (1/20 mile, or about 80 meters), you can do this:

NSMutableArray *locationsWithinOneBlock = [NSMutableArray new];
for (CLLocation *location in myLocations) {
    if ([location distanceFromLocation:targetLocation] <= 80.0)
        [locationsWithinOneBlock addObject:location];
}

This assumes you have an array myLocations of CLLocation objects that you want to filter against a single CLLocation called targetLocation.

Upvotes: 1

Related Questions