-->

Distance between two coordinates with CoreLocation

2019-02-02 07:48发布

问题:

I need to calculate the distance (in meters and miles) between two coordinates given

How can I do that?

回答1:

Returns the distance (in meters) from the receiver’s coordinate to the coordinate of the specified location.

// Deprecated in iOS 3.2 method
- (CLLocationDistance)getDistanceFrom:(const CLLocation *)location

// Correct method
- (CLLocationDistance)distanceFromLocation:(const CLLocation *)location

CLLocation



回答2:

The method in the previous answer has been deprecated in iOS 3.2. The new method is the very similar

- (CLLocationDistance)distanceFromLocation:(const CLLocation *)location

which also returns a distance in meters. It's accounting for the curvature of the earth.



回答3:

swift 3 func distance(from location: CLLocation) -> CLLocationDistance Description Returns the distance (measured in meters) from the receiver’s location to the specified location. This method measures the distance between the two locations by tracing a line between them that follows the curvature of the Earth. The resulting arc is a smooth curve and does not take into account specific altitude changes between the two locations. Parameters
location The other location. Returns The distance (in meters) between the two locations. SDKs iOS 3.2+, macOS 10.6+, tvOS 9.0+, watchOS 2.0+ Declared In Core Location More Method Reference

e.g.

let distance = location.distance(from: CLLocation(latitude: 
CLLocationDegrees(oldLocationLat), longitude: 
CLLocationDegrees(oldLocationLng)))


回答4:

swift 3

func distance(from location: CLLocation) -> CLLocationDistance Description 

Returns the distance (measured in meters)

e.g.

locations: [CLLocation]

let location: CLLocation = locations.last!

let distance = location.distance(from: CLLocation(latitude: CLLocationDegrees(oldLocationLat), longitude: CLLocationDegrees(oldLocationLng)))