Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CLGeocoder returning locations in other countries

I have the following code:

CLGeocoder *_geo = [[CLGeocoder alloc] init];
CLRegion *region = [[CLRegion alloc] initCircularRegionWithCenter: CLLocationCoordinate2DMake(37.33233141, -122.03121860) radius:100 identifier:@"San Francisco"];
[_geo geocodeAddressString:@"Starbucks" inRegion:region
             completionHandler:^(NSArray *placemarks, NSError *error)
{
    NSLog("%@", placemarks);
}];

This returns a Starbucks location in the Philippines even though the center is in the middle of San Francisco.

(NSArray *) $3 = 0x07cd9d10 <__NSArrayM 0x7cd9d10>(
Starbuck's, Metro Manila, Quezon City, Republic of the Philippines @ <+14.63617752,+121.03067530> +/- 100.00m, region (identifier <+14.63584900,+121.02951050> radius 166.35) <+14.63584900,+121.02951050> radius 166.35m
)

Any ideas?

like image 322
ninjaneer Avatar asked Apr 18 '12 03:04

ninjaneer


1 Answers

Here is a workaround that is working for me. I'm using geocodeAddressString: completionHandler: without taking regions into account.

After that, I build an array of placemarks based on the returned one but only including the nearest ones.

Note that this code doesn't check if there has been an error. I've removed it to make it simpler.

CLLocation *centerLocation = [[CLLocation alloc] initWithLatitude:37.33233141 longitude:-122.03121860];

CLLocationDistance maxDistance = <YOUR_MAX_DISTANCE>;

CLGeocoder *geo = [[CLGeocoder alloc] init];
[geo geocodeAddressString:addressString
        completionHandler:^(NSArray *placemarks, NSError *error)
{
    NSMutableArray *filteredPlacemarks = [[NSMutableArray alloc] init];
    for (CLPlacemark *placemark in placemarks)
    {
        if ([placemark.location distanceFromLocation:centerLocation] <= maxDistance)
        {
            [filteredPlacemarks addObject:placemark];
        }
    }

    // Now do whatever you want with the filtered placemarks.
}];

Alternatively, if you want to keep working with regions: instead of comparing distances with distanceFromLocation:, you can use CLRegion's containsCoordinate:.

Hope it helps.

like image 175
msoler Avatar answered Sep 30 '22 18:09

msoler