-2

I have a label in my detailView i want to calculate distance from the current user location ( will update if user moves ) to a certain annotation .
And show the distance in that label
E.g : "3.6 km from your location "

  • Possible duplicate of [How to find out distance between coordinates?](https://stackoverflow.com/questions/33304340/how-to-find-out-distance-between-coordinates) – Anton Belousov May 31 '17 at 23:40

2 Answers2

1

I recommend using extensions. Lets say you have your own class for Annotations (if you don't, just use MKAnnotation instead of "YourAnnotationClass") - you want to extend it with calculated property distanceToUsersCurrentLocation. Obviously, to access user's current location you need to import CoreLocation.

import UIKit
import CoreLocation

public class ViewController { //class where you need to set the label's text

    //your code here

    }
}

extension YouAnnotationClass {
    var distanceToUsersCurrentLocation: Double {
        let manager = CLLocationManager() //location manager for user's current location
        let destinationCoordinates = CLLocation(latitude: self.latitude, longitude: self.longitude) //coordinates for destinastion
        let selfCoordinates = CLLocation(latitude: (manager.location?.coordinate.latitude)!, longitude: (manager.location?.coordinate.longitude)!) //user's location
        return selfCoordinates.distance(from: destinationCoordinates) //return distance in **meters**
}

Everytime you access distanceToUsersCurrentLocation within this class, you'll get distance in meters. I hope this helped with your problem

Kordian
  • 33
  • 3
0

Your annotation will have a location property. Two work out the distance between the points -

let distanceInMeters = coordinateOne.distance(from: coordinateTwo)

You can read this link for more information -

How to find out distance between coordinates?