blob: 99a5f29ff074031d35f14b37b54295dad87e324a (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
|
//
// Haversine.swift
// RelaySelector
//
// Created by Marco Nikic on 2023-06-29.
// Copyright © 2025 Mullvad VPN AB. All rights reserved.
//
import Foundation
import MullvadTypes
public enum Haversine {
/// Approximation of the radius of the average circumference,
/// where the boundaries are the meridian (6367.45 km) and the equator (6378.14 km).
static let earthRadiusInKm = 6372.8
/// Implemented as per https://rosettacode.org/wiki/Haversine_formula#Swift
/// Computes the great circle distance between two points on a sphere.
///
/// The inputs are converted to radians, and the output is in kilometers.
/// - Parameters:
/// - lat1: The first point's latitude
/// - lon1: The first point's longitude
/// - lat2: The second point's latitude
/// - lon2: The second point's longitude
/// - Returns: The haversine distance between the two points.
static func distance(
_ latitude1: Double,
_ longitude1: Double,
_ latitude2: Double,
_ longitude2: Double
) -> Double {
let dLat = latitude1.toRadians - latitude2.toRadians
let dLon = longitude1.toRadians - longitude2.toRadians
let haversine =
sin(dLat / 2).squared + sin(dLon / 2)
.squared * cos(latitude1.toRadians) * cos(latitude2.toRadians)
let c = 2 * asin(sqrt(haversine))
return Self.earthRadiusInKm * c
}
}
extension Double {
var toRadians: Double { self * Double.pi / 180.0 }
var toDegrees: Double { self * 180.0 / Double.pi }
var squared: Double { pow(self, 2.0) }
}
|