Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort a list by distance using reversed Geolocation

I'm using Xcode 7 with iOS9. I want to sort a list ascending, based on distance from users current location to all other locations in the list.

I don't want to calculate the distance to a location by coordinates, but by address because the distance depends on the choosen method (drive / walk). All I want to do is save the address in each location object to calculate the distance to that object later on.

When initializing the list with objects I'm doing this request in each object's initializer:

let location = CLLocation(latitude: latitude, longitude: longitude) //changed!!!

CLGeocoder().reverseGeocodeLocation(location, completionHandler: {(placemarks, error) -> Void in 
    //the code to obtain an address and save it in a location object is here and works
}

The problem I have now is that I have to send 172 such reverseGeocodeLocation requests as my list contains 172 objects and I need to calculate the distance from my users location to each object's location.

Sending so many requests so fast results in this error: The operation couldn’t be completed. (kCLErrorDomain error 2.)

Is there a way to solve this? If things aren't clear tell me please so I can clarify

like image 433
newbiedevelopper Avatar asked Sep 25 '22 21:09

newbiedevelopper


1 Answers

Apple's geocoding object is not intended for bulk-geocoding. See the CLGeocoder Class Reference in Xcode for more information. A brief excerpt:

Applications should be conscious of how they use geocoding. Geocoding requests are rate-limited for each app, so making too many requests in a short period of time may cause some of the requests to fail. (When the maximum rate is exceeded, the geocoder returns an error object with the value kCLErrorNetwork to the associated completion handler.) Here are some rules of thumb for using this class effectively:

Send at most one geocoding request for any one user action.

If the user performs multiple actions that involve geocoding the same location, reuse the results from the initial geocoding request instead of starting individual requests for each action.

When you want to update the user’s current location automatically (such as when the user is moving), issue new geocoding requests only when the user has moved a significant distance and after a reasonable amount of time has passed. For example, in a typical situation, you should not send more than one geocoding request per minute.

(Emphasis added by me.)

The summary is that you can't do what you are trying to do with Apple's CLGeocoder class.

You are only supposed to submit a single geocoding request for a user action, and then typically no more than one geocoding request per minute.

You'll need to license a third party geocoding service (and probably pay for it) in order to do bulk geocoding or reverse-geocoding.

like image 66
Duncan C Avatar answered Sep 29 '22 05:09

Duncan C