MapKit annotations and user location

I followed this tutorial to make my first application:

http://icodeblog.com/2009/12/21/introduction-to-mapkit-in-iphone-os-3-0/

I would really like to know how to sort the annotations in a table in order of distance to the user (nearest annotation is the first in the table). How can I do that?

I understand that I have to use CLLocation to find the user's location, but then I have no idea.

Can anyone help me?

Greetings,

Thank you in advance for your much appreciated help,

EDIT: I added details:

the data is not in the array, it is implemented in RootViewController.m in this form:

-(void)loadOurAnnotations
{
    CLLocationCoordinate2D workingCoordinate;

    workingCoordinate.latitude = 40.763856;
    workingCoordinate.longitude = -73.973034;
    iCodeBlogAnnotation *appleStore1 = [[iCodeBlogAnnotation alloc] 

    initWithCoordinate:workingCoordinate];
    [appleStore1 setTitle:@"Apple Store 5th Ave."];
    [appleStore1 setSubtitle:@"Apple Flagship Store"];
    [appleStore1 setAnnotationType:iCodeBlogAnnotationTypeApple];

    [mapView addAnnotation:appleStore1];

      

... etc. How can this be done then?

You can find the source code here:

icodeblog.com/wp-content/uploads/2009/09/iCodeMap.zip

teddafan

+2


a source to share


2 answers


On CLLocation

you can use

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

      



to calculate the distance of an object from another. In this case, it will presumably be the user's current location.

If the data is in NSArray

, you can use sortedArrayUsingFunction

to call a helper function that calls this method.

+3


a source


Scroll through the CLLocations and find the distance between them and your current location.

Then use your own sorting algorithm to sort the distances you have in the array.



for (CLLocation *loc in locations) {
  [distances addobject:[currentLocation distanceFromLocation:loc]];
}
[distances sort]; /* Own sorting algorithm */
[yourTable reloadData];

      

+1


a source







All Articles