Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 4043278
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 20, 20262026-05-20T13:06:27+00:00 2026-05-20T13:06:27+00:00

I have a MKMapView, and I would like to know how I can find

  • 0

I have a MKMapView, and I would like to know how I can find the nearest 5 annotations to the user, and only display them on the MKMapView.

My code currently is:

- (void)loadFiveAnnotations {
    NSString *string = [[NSString alloc] initWithContentsOfURL:url];
    string = [string stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    NSArray *chunks = [string componentsSeparatedByString:@";"];
    NSArray *keys = [NSArray arrayWithObjects:@"type", @"name", @"street", @"address1", @"address2", @"town", @"county", @"postcode", @"number", @"coffeeclub", @"latlong", nil];   
    // max should be a multiple of 12 (number of elements in keys array)
    NSUInteger max = [chunks count] - ([chunks count] % [keys count]);
    NSUInteger i = 0;

    while (i < max)
    {
        NSArray *subarray = [chunks subarrayWithRange:NSMakeRange(i, [keys count])];
        NSDictionary *dict = [[NSDictionary alloc] initWithObjects:subarray forKeys:keys];
        // do something with dict
        NSArray *latlong = [[dict objectForKey:@"latlong"] componentsSeparatedByString:@","];
        NSString *latitude = [[latlong objectAtIndex:0] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
        NSString *longitude = [[latlong objectAtIndex:1] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
        CLLocationDegrees lat = [latitude floatValue];
        CLLocationDegrees longi = [longitude floatValue];
        Annotation *annotation = [[Annotation alloc] initWithCoordinate:CLLocationCoordinate2DMake(lat, longi)];
        annotation.title = [dict objectForKey:@"name"];
        annotation.subtitle = [NSString stringWithFormat:@"%@, %@, %@",[dict objectForKey:@"street"],[dict objectForKey:@"county"], [dict objectForKey:@"postcode"]];
        [mapView addAnnotation:annotation];
        [dict release];

        i += [keys count];
    }
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-20T13:06:27+00:00Added an answer on May 20, 2026 at 1:06 pm

    A long answer, already mostly written when Stephen Poletto posted and containing example code on how to use the built-in methods for sorting an array, so I though it was still worth posting though the essential answer is the same (ie, “pick the five closest for yourself, pass only those on”):

    You’re going to need to sort your annotations by distance for yourself, and submit only the closest five to the MKMapView. If you have two CLLocations then you can get the distance between them using the distanceFromLocation: method (which was getDistanceFrom: prior to iOS 3.2; that name is now deprecated).

    So, for example, supposing your Annotation class had a method ‘setReferenceLocation:’ to which you pass a CLLocation and a getter ‘distanceFromReferenceLocation’ which returns the distance between the two, you could do:

    // create and populate an array containing all potential annotations
    NSMutableArray *allPotentialAnnotations = [NSMutableArray array];
    
    for(all potential annotations)
    {
        Annotation *annotation = [[Annotation alloc]
                                                initWithCoordinate:...whatever...];
        [allPotentialAnnotations addObject:annotation];
        [annotation release];
    }
    
    // set the user's current location as the reference location
    [allPotentialAnnotations
          makeObjectsPerformSelector:@selector(setReferenceLocation:) 
          withObject:mapView.userLocation.location];
    
    // sort the array based on distance from the reference location, by
    // utilising the getter for 'distanceFromReferenceLocation' defined
    // on each annotation (note that the factory method on NSSortDescriptor
    // was introduced in iOS 4.0; use an explicit alloc, init, autorelease
    // if you're aiming earlier)
    NSSortDescriptor *sortDescriptor = 
                  [NSSortDescriptor
                      sortDescriptorWithKey:@"distanceFromReferenceLocation" 
                      ascending:YES];
    
    [allPotentialAnnotations sortUsingDescriptors:
                              [NSArray arrayWithObject:sortDescriptor]];
    
    // remove extra annotations if there are more than five
    if([allPotentialAnnotations count] > 5)
    {
        [allPotentialAnnotations
                   removeObjectsInRange:NSMakeRange(5, 
                               [allPotentialAnnotations count] - 5)];
    }
    
    // and, finally, pass on to the MKMapView
    [mapView addAnnotations:allPotentialAnnotations];
    

    Depending on where you’re loading from, you made need to create a local store (in memory or on disk) for annotations and select the five nearest whenever the user moves. Either register yourself as a CLLocationManager delegate or key-value observe on the map view’s userLocation property. If you have quite a lot of potential annotations then sorting all of them is a bit wasteful and you’d be better advised to use a quadtree or a kd-tree.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

How can I have my MKMapView follow my user around until they scroll, and
Hi I would like to have an explanation regarding the following code. Here Sometimes
I have added an mkpinannotation in an mkmapview. I would like to move the
As well as my question Removing MKMapView Annotations causes leaks. I have discovered that
I think my question is fairly clear, I would like to know if every
I have an MKMapView and am adding an overlay (MKOverlay) to it. I would
I would like to further annotate the custom markers I have placed on a
I simply would like to display icon that is in fixed location in MapView.
In the app I'm currently designing I have a MKMapView with overlays on it
I would like to have a Context Menu on my MapView and let the

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.