Mapview Showing Closest location

176 Views Asked by At

Building an iPhone app for a business with multiple locations. I have a mapview that shows all the locations, I got it to work to show the locations on the map. Zooming out you see all locations that I have specified. Issue is I need it to show closest location first to the current location of the customer.

Key points: 1. Using property-list (config.plist) to specify the locations. 2. It does show the blue dot for current location and that is accurate. When zooming out and selecting any of the location I have it set to take you to google maps and that is all accurate from current location to that specific business location. 3. This is for iPhone using of course xcode.

Thanks.

2

There are 2 best solutions below

0
On

Just to give you a start with some code, here is an example of a method that iterates through all your locations and returns the closest one.

-(YourModel*)getClosestLocation
{
    CLLocation *myLocation = currentLocation //This is the current location you should get from the GPS
    NSArray *allLocations = myModelArray; //array with all locations you want to compare

    YourModel *closestLocation = nil;
    CLLocationDistance closestDistance = CGFLOAT_MAX;

    for (YourModel* model in allLocations) 
    {
        CLLocation *modelLocation = [[CLLocation alloc] initWithLatitude:model.latitude longitude:model.longitude];
        CLLocationDistance distance = [myLocation distanceFromLocation:modelLocation];
        if (distance < closestDistance) {
            closestLocation = modelLocation;
            closestDistance = distance;
        }
    }

    return closestLocation;
}

please, give some feedback if it helped.

0
On

This seems pretty simple, iterate through the locations, calculate the distance to current location, find the shortest one (keep track of it during iteration), set map to zoom to show the bounding box of user location and closest location.