1

I am using a MapView with some pins inside a city added. Also, the current user location is displayed in the map. With these two things known (user location and pins) I would like to show in a label the nearest pin from where the user is.

javierdemartin
  • 595
  • 6
  • 24
  • possible duplicate of [Find nearest annotations from user location ios?](http://stackoverflow.com/questions/22452509/find-nearest-annotations-from-user-location-ios) – ridvankucuk Aug 31 '15 at 11:44
  • Thanks, I couldn't find anything related. I don't know anything at all about Objective-C but I am going to check it out. – javierdemartin Aug 31 '15 at 13:12

3 Answers3

7

There is no direct API to find that. You have to loop through all annotations.

let pins = mapView.annotations as! [MKAnnotation]
let currentLocation = mapView.userLocation.location!

let nearestPin: MKAnnotation? = pins.reduce((CLLocationDistanceMax, nil)) { (nearest, pin) in
    let coord = pin.coordinate
    let loc = CLLocation(latitude: coord.latitude, longitude: coord.longitude)
    let distance = currentLocation.distanceFromLocation(loc)
    return distance < nearest.0 ? (distance, pin) : nearest
}.1

// Here, `nearestPin` is `nil` iff there is no annotations on the map.

If you don't know the reduce method, see the docs.

rintaro
  • 51,423
  • 14
  • 131
  • 139
1

Use distanceFromLocation to calculate all the distance:

let distance = fromLocation.distanceFromLocation(toLocation)

you could calculate the distances for each pin in a for cycle, so to find the slower one

take a look at this: Find nearest annotations from user location ios?

Community
  • 1
  • 1
Alberto Scampini
  • 798
  • 9
  • 27
0

You might look at something like the Mapbox Distance API to do this in a single REST request: https://www.mapbox.com/blog/distance-api/

incanus
  • 5,100
  • 1
  • 13
  • 20