0

I have list a of places with coordinates
If users select particular location I want to suggest list of locations nearby using coordinates I can achieve that by putting loop and searching all the places within the distance from the following code

  for(i=0;i<locations.count;i++)
 CLLocation *locA = [[CLLocation alloc] initWithLatitude:lat1 longitude:long1];

 CLLocation *locB = [[CLLocation alloc] initWithLatitude:lat2 longitude:long2];

 CLLocationDistance distance = [locA distanceFromLocation:locB];
// if(distance<10)
 //{
 //show the pin
// }

But I guess It not a efficient way if we have more locations in the database What I can I do here

Is there any alternative way??

AlgoCoder
  • 1,706
  • 5
  • 19
  • 40
  • What database? What are the objects? Your code uses undefined variables, what are they? – Wain Mar 14 '14 at 10:31
  • @Wain I am using SQL database. I have a details of each locations name,latitude,longitude and category. I've put the undefined variable just give a view on my idea that, I have to calculate the distance for every locations object and check the distance to make it visible on the map – AlgoCoder Mar 14 '14 at 10:38

1 Answers1

1

You should filter the content to reduce the amount you extract from the database. You need to define what 'nearby' means in your case, calculate the lat/long bounding box where everything outside that box is not 'nearby' and use the box min and max lat/long values to exclude things that don't match. This is done as part of the SQL query so it's very efficient.

Now, your question loop logic comes into play. The approach is fine, though using your own loop likely isn't best. Instead, look at using sortedArrayUsingComparator: or sortedArrayUsingFunction:context:.

Wain
  • 118,658
  • 15
  • 128
  • 151
  • Thanks,In my case 'nearby' means all locations within 2 miles – AlgoCoder Mar 14 '14 at 10:55
  • Also consider `NSPredicate` for searching the data, loops are never the way to go. – Sammio2 Mar 17 '14 at 22:04
  • @Sammio2, the whole point of my answer is that all filtering is done in SQL rather than code, so no predicate is required (SQL filter is much more efficient). The loop for sorting is also recommended to be replaced (though that mostly just saves code as the sort will iterate internally...). – Wain Mar 17 '14 at 23:03
  • Ahh yes, sorry I totally misread the initial question, presumed that a certain amount of filtering was already being done in the SQL Query. My mistake! – Sammio2 Mar 18 '14 at 09:01