In this quick tip, I show you how to calculate the distance between two locations using the Core Location framework. Let's say you have two sets of coordinates and you want to calculate the distance between them. In this example, we use a tuple to store the latitude and the longitude of a set of coordinates.

let coordinatesA = (latitude: 50.88194, longitude: 4.68139)
let coordinatesB = (latitude: 50.87921, longitude: 4.67374)

To calculate the distance between them, we need the Core Location framework so we add an import statement for the Core Location framework.

import CoreLocation

let coordinatesA = (latitude: 50.88194, longitude: 4.68139)
let coordinatesB = (latitude: 50.87921, longitude: 4.67374)

The method we use to calculate the distance between the locations is defined on the CLLocation class so we convert each set of coordinates to a CLLocation instance.

import CoreLocation

let coordinatesA = (latitude: 50.88194, longitude: 4.68139)
let coordinatesB = (latitude: 50.87921, longitude: 4.67374)

let locationA = CLLocation(latitude: coordinatesA.latitude, longitude: coordinatesA.longitude)
let locationB = CLLocation(latitude: coordinatesB.latitude, longitude: coordinatesB.longitude)

To calculate the distance between the CLLocation instances, we invoke distance(from:) on locationA, passing in a reference to locationB. That's it.

import CoreLocation

let coordinatesA = (latitude: 50.88194, longitude: 4.68139)
let coordinatesB = (latitude: 50.87921, longitude: 4.67374)

let locationA = CLLocation(latitude: coordinatesA.latitude, longitude: coordinatesA.longitude)
let locationB = CLLocation(latitude: coordinatesB.latitude, longitude: coordinatesB.longitude)

locationA.distance(from: locationB)

The return value of the distance(from:) method is of type CLLocationDistance, a type alias for Double. The return value is the distance in meters between the locations.

618.1407804408766