Skip to content

Instantly share code, notes, and snippets.

@dsaiztc
Last active January 21, 2019 09:11
Show Gist options
  • Save dsaiztc/20704d1b14269095b0ff to your computer and use it in GitHub Desktop.
Save dsaiztc/20704d1b14269095b0ff to your computer and use it in GitHub Desktop.
Calculate distance between two GPS points.
/**
* Calculate distance between two gps points based in Haversine formula: http://en.wikipedia.org/wiki/Haversine_formula
*
* @param latitude1 GPS point 1 Latitude
* @param longitude1 GPS point 1 Longitude
* @param latitude2 GPS point 2 Latitude
* @param longitude2 GPS point 1 Longitude
* @return Distance in kilometers (km)
*/
static double haversineDistance(float latitude1, float longitude1, float latitude2, float longitude2)
{
double h = (1 - Math.cos(latitude1 * Math.PI / 180 - latitude2 * Math.PI / 180)) / 2 + Math.cos(latitude2 * Math.PI / 180) * Math.cos(latitude1 * Math.PI / 180) * (1 - Math.cos(longitude1 * Math.PI / 180 - longitude2 * Math.PI / 180)) / 2;
h += 2 * 6367.45 * Math.asin(Math.sqrt(h));
return h;
}
import numpy as np
def haversine_np(lon1, lat1, lon2, lat2):
"""
Calculate the great circle distance between two points
on the earth (specified in decimal degrees)
All args must be of equal length.
"""
lon1, lat1, lon2, lat2 = map(np.radians, [lon1, lat1, lon2, lat2])
dlon = lon2 - lon1
dlat = lat2 - lat1
a = np.sin(dlat/2.0)**2 + np.cos(lat1) * np.cos(lat2) * np.sin(dlon/2.0)**2
c = 2 * np.arcsin(np.sqrt(a))
km = 6367 * c
return km
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment