Skip to content

Commit ca3e4bf

Browse files
authored
Add the haversine formula (#194)
1 parent 7423a4a commit ca3e4bf

File tree

2 files changed

+60
-0
lines changed

2 files changed

+60
-0
lines changed
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
using System;
2+
3+
using Algorithms.Other;
4+
5+
using NUnit.Framework;
6+
using NUnit.Framework.Internal;
7+
8+
namespace Algorithms.Tests.Other
9+
{
10+
public static class GeoLocationTests
11+
{
12+
[Test]
13+
[TestCase(53.430488d, -2.96129d, 53.430488d, -2.96129d, 0d)]
14+
[TestCase(53.430971d, -2.959806d, 53.430242d, -2.960830d, 105d)]
15+
public static void CalculateDistanceFromLatLngTest(double lat1, double lng1, double lat2, double lng2, double expectedValue)
16+
{
17+
var result = GeoLocation.CalculateDistanceFromLatLng(lat1, lng1, lat2, lng2);
18+
var actualValue = Convert.ToDouble(result);
19+
20+
// Assert
21+
Assert.AreEqual(expectedValue, actualValue, 1d); // Accept if distance diff is +/-1 meters.
22+
}
23+
}
24+
}

Algorithms/Other/GeoLocation.cs

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
using System;
2+
using System.Collections.Generic;
3+
using System.Text;
4+
5+
namespace Algorithms.Other
6+
{
7+
public static class GeoLocation
8+
{
9+
private const double EarthRadiusKm = 6371.01d;
10+
11+
/// <summary>
12+
/// Calculates spherical distance between 2 points given their latitude, longitude coordinates. https://www.movable-type.co.uk/scripts/latlong.html.
13+
/// </summary>
14+
/// <param name="lat1">Latitude of point A.</param>
15+
/// <param name="lng1">Longitude of point A.</param>
16+
/// <param name="lat2">Latitude of point B.</param>
17+
/// <param name="lng2">Longitude of point B.</param>
18+
/// <returns>Spherical distance between A and B.</returns>
19+
public static double CalculateDistanceFromLatLng(double lat1, double lng1, double lat2, double lng2)
20+
{
21+
var pi180 = Math.PI / 180d;
22+
var lat1Radian = lat1 * pi180;
23+
var lng1Radian = lng1 * pi180;
24+
var lat2Radian = lat2 * pi180;
25+
var lng2Radian = lng2 * pi180;
26+
27+
var diffLat = lat2Radian - lat1Radian;
28+
var diffLng = lng2Radian - lng1Radian;
29+
30+
var haversine = Math.Sin(diffLat / 2) * Math.Sin(diffLat / 2) + Math.Cos(lat1Radian) * Math.Cos(lat2Radian) * Math.Sin(diffLng / 2) * Math.Sin(diffLng / 2);
31+
var distance = EarthRadiusKm * (2d * Math.Atan2(Math.Sqrt(haversine), Math.Sqrt(1 - haversine)));
32+
33+
return distance * 1000; // Convert from km -> m
34+
}
35+
}
36+
}

0 commit comments

Comments
 (0)