82

I want to make it so that it will show the amount of distance between two CLLocation coordinates. Is there someway to do this without a complex math formula? If there isn't how would you do it with a formula?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
John Doe
  • 1,609
  • 2
  • 13
  • 22

10 Answers10

242

CLLocation has a distanceFromLocation method so given two CLLocations:

CLLocationDistance distanceInMeters = [location1 distanceFromLocation:location2];

or in Swift 4:

//: Playground - noun: a place where people can play

import CoreLocation


let coordinate₀ = CLLocation(latitude: 5.0, longitude: 5.0)
let coordinate₁ = CLLocation(latitude: 5.0, longitude: 3.0)

let distanceInMeters = coordinate₀.distance(from: coordinate₁) // result is in meters

you get here distance in meter so 1 miles = 1609 meter

if(distanceInMeters <= 1609)
 {
 // under 1 mile
 }
 else
{
 // out of 1 mile
 }
Justin Vallely
  • 5,932
  • 3
  • 30
  • 44
Glenn Howes
  • 5,447
  • 2
  • 25
  • 29
  • How would I convert this into miles? – John Doe Oct 23 '15 at 14:12
  • Oh wait I got it! Thanks. (: – John Doe Oct 23 '15 at 14:15
  • 5
    According to Google, there are 0.000621371 miles in a meter. So, I'd suggest multiplying it by 0.000621371. – Glenn Howes Oct 23 '15 at 14:15
  • Ok great, thanks! I'll accept your answer in a few minutes when it will let me. – John Doe Oct 23 '15 at 14:15
  • some times its showing wrong distance i checked with google map with same locations which i have given the same locations in the code. please any other way to calculate distance let me know please. – vijay Feb 24 '17 at 12:58
  • Well, how far off is it? – Glenn Howes Feb 24 '17 at 18:52
  • 1
    This is not the true distance "By road" According to apple Docs - "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." https://developer.apple.com/documentation/corelocation/cllocation/1423689-distance .. so if you're looking for driving distance, the reliable way to find the correct distance so far has been Google Maps Distance Matrix API or MKRoute. – Anjan Biswas Jul 17 '17 at 23:57
  • @Annjawn That really has nothing to do with the question as asked. – Glenn Howes Jul 18 '17 at 18:35
  • 1
    @GlennHowes yes it does, chances are that the OP is trying to find the driving (or other mode of transport) distance between two points in which case just a Geospatial distance as is derived by `distanceFromLocation` will be completely incorrect. For Driving distance, the correct implementation would be to use `MKRoute` which will give you the "Route Distance" `distance` in meters along with other stuff like expected travel time, transport type etc - https://developer.apple.com/documentation/mapkit/mkroute – Anjan Biswas Jul 18 '17 at 18:44
  • 1
    And as reported by @vijay (in comments above) this is the reason why his distances are incorrect when compared to Google Map. Google map and MKRoute will consider the route information to calculate the actual transport distance whereas the simple `distanceFromLocation` won't, so I suggest you update your answer to clarify this in order to avoid confusing people who reach this page through google. – Anjan Biswas Jul 18 '17 at 18:57
  • How can i do that with a place with 2 Coordinates ? – Muhammed Dec 31 '17 at 23:09
  • No, it's just a math calculation. It isn't a turn by turn database lookup. – Glenn Howes Apr 29 '18 at 03:26
  • let distanceInMiles = coordinate.distance(from:currentDeviceCoordinate) / 1609.344 // result is in miles – Gurjinder Singh May 24 '18 at 12:17
20

Swift 4.1

import CoreLocation

//My location
let myLocation = CLLocation(latitude: 59.244696, longitude: 17.813868)

//My buddy's location
let myBuddysLocation = CLLocation(latitude: 59.326354, longitude: 18.072310)

//Measuring my distance to my buddy's (in km)
let distance = myLocation.distance(from: myBuddysLocation) / 1000

//Display the result in km
print(String(format: "The distance to my buddy is %.01fkm", distance))
Tieda Wei
  • 588
  • 5
  • 14
10

Try this out:

distanceInMeters = fromLocation.distanceFromLocation(toLocation)
distanceInMiles = distanceInMeters/1609.344

From Apple Documentation:

Return Value: The distance (in meters) between the two locations.

Abhinav
  • 37,684
  • 43
  • 191
  • 309
  • Is there a way to turn it into miles? – John Doe Oct 23 '15 at 14:13
  • Also from apple docs - "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."https://developer.apple.com/documentation/corelocation/cllocation/1423689-distance – Anjan Biswas Jul 17 '17 at 23:52
  • Good, that you use the correct factor `1609.344`. https://en.wikipedia.org/wiki/Mile – thetrutz May 09 '20 at 07:38
  • 1
    For iOS 10+, it would be useful to perform the conversion to miles via the `Measurement` class: `let miles = Measurement(value: meters, unit: UnitLength.meters).converted(to: UnitLength.miles).value` – gyratory circus Dec 27 '20 at 05:59
7
import CoreLocation

//My location
let myLocation = CLLocation(latitude: 31.5101892, longitude: 74.3440842)

//My Next Destination
let myNextDestination = CLLocation(latitude: 33.7181584, longitude: 73.071358)

//Finding my distance to my next destination (in km)
let distance = myLocation.distance(from: myNextDestination) / 1000
Ali Aqdas
  • 437
  • 5
  • 9
3
func calculateDistanceInMiles(){

    let coordinate₀ = CLLocation(latitude:34.54545, longitude:56.64646)
    let coordinate₁ = CLLocation(latitude: 28.4646, longitude:76.65464)
    let distanceInMeters = coordinate₀.distance(from: coordinate₁)
    if(distanceInMeters <= 1609)
    {
        let s =   String(format: "%.2f", distanceInMeters)
        self.fantasyDistanceLabel.text = s + " Miles"
    }
    else
    {
        let s =   String(format: "%.2f", distanceInMeters)
        self.fantasyDistanceLabel.text = s + " Miles"

    }
}
  • 4
    While this code may answer the question, providing additional context regarding why and/or how this code answers the question improves its long-term value. – rollstuhlfahrer Apr 27 '18 at 11:51
3

For swift 4

   let locationOne = CLLocation(latitude: lat, longitude: long)
   let locationTwo = CLLocation(latitude: lat,longitude: long)

  let distance = locationOne.distance(from: locationTwo) * 0.000621371

  distanceLabel.text = "\(Int(round(distance))) mi"
Faris
  • 1,206
  • 1
  • 12
  • 18
1

For objective-c

You can use distanceFromLocation to find the distance between two coordinates.

Code Snippets:

CLLocation *loc1 = [[CLLocation alloc] initWithLatitude:lat1 longitude:lng1];

CLLocation *loc2 = [[CLLocation alloc] initWithLatitude:lat2 longitude:lng2];

CLLocationDistance distance = [loc1 distanceFromLocation:loc2];

Your output will come in meters.

Shoaib
  • 1,295
  • 15
  • 22
Vijay
  • 791
  • 1
  • 8
  • 23
  • the question here is captioned with 'swift'. So maybe you need to update your answer, or add "For objective-c :" @Vijay – Dory Daniel Mar 01 '17 at 10:33
1
import UIKit
import CoreLocation

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        var currentLocation = CLLocation(latitude: 23.1929, longitude: 72.6156)
        var DestinationLocation = CLLocation(latitude: 23.0504, longitude: 72.4991)
        var distance = currentLocation.distance(from: DestinationLocation) / 1000
        print(String(format: "The distance to my buddy is %.01fkm", distance))
    }
}
  • While this code may answer the question, it would be better to explain how it solves the problem without introducing others and why to use it. Code-only answers are not useful in the long run. – koen Nov 21 '19 at 13:33
1

You can also use the HaversineDistance algorithm just like android developers used, this is helpfull when you have antother app in android similar to it, else above answer is correct for you.

import UIKit

func haversineDinstance(la1: Double, lo1: Double, la2: Double, lo2: Double, radius: Double = 6367444.7) -> Double {

let haversin = { (angle: Double) -> Double in
    return (1 - cos(angle))/2
}

let ahaversin = { (angle: Double) -> Double in
    return 2*asin(sqrt(angle))
}

// Converts from degrees to radians
let dToR = { (angle: Double) -> Double in
    return (angle / 360) * 2 * .pi
}

let lat1 = dToR(la1)
let lon1 = dToR(lo1)
let lat2 = dToR(la2)
let lon2 = dToR(lo2)

return radius * ahaversin(haversin(lat2 - lat1) + cos(lat1) * cos(lat2) * haversin(lon2 - lon1))
}

let amsterdam = (52.3702, 4.8952)
let newYork = (40.7128, -74.0059)

// Google says it's 5857 km so our result is only off by 2km which could be due to all kinds of things, not sure how google calculates the distance or which latitude and longitude google uses to calculate the distance.
haversineDinstance(la1: amsterdam.0, lo1: amsterdam.1, la2: newYork.0, lo2: newYork.1)

I have picked the code written above from the refrence link https://github.com/raywenderlich/swift-algorithm-club/blob/master/HaversineDistance/HaversineDistance.playground/Contents.swift

Sazid Iqabal
  • 409
  • 2
  • 21
-2

Swift 5.

func calculateDistance(mobileLocationX:Double,mobileLocationY:Double,DestinationX:Double,DestinationY:Double) -> Double {

        let coordinate₀ = CLLocation(latitude: mobileLocationX, longitude: mobileLocationY)
        let coordinate₁ = CLLocation(latitude: DestinationX, longitude:  DestinationY)

        let distanceInMeters = coordinate₀.distance(from: coordinate₁)

        return distanceInMeters
    }

use to

let distance = calculateDistance("add parameters")
ikbal
  • 1,110
  • 12
  • 21