This code can to calculate the distance between two points using latitude and longitude.
<?php
use HaversineFormula\Distance;
$inKilometers = Distance::toKilometers(30.261699, -97.738967, 29.869229, -97.959595);
$inMiles = Distance::toMiles(30.261699, -97.738967, 29.869229, -97.959595);
/*
* @param lat1 (double) latitude of origin
* @param lon1 (double) longitude of origin
* @param lat2 (double) latitude of destination
* @param lon2 (double) longitude of destination
* @param unit (enum) MILE, MI for miles or KILOMETER, KM for kilometers
* @return (double) Distance between the two points in the units specified.
*/
FUNCTION DISTANCE( lat1 DOUBLE, lon1 DOUBLE, lat2 DOUBLE, lon2 DOUBLE, unit ENUM( 'MILE', 'KILOMETER', 'MI', 'KM' ) )
Calculate the distance between San Francisco, CA and New York, NY in miles
mysql> SELECT DISTANCE( 37.7756, -122.4193, 40.71448, -74.00598, 'MI' );
2565.80921930121
Find the two closest cities (in our table) to Paris, France
mysql> SELECT city, country FROM cities ORDER BY DISTANCE( 48.856638, 2.352241, cities.lat, cities.lon, 'KM' ) ASC LIMIT 2;
Geneva Switzerland
Barcelona Spain
double distance = HaversineFormula.distance(51.5112139, -0.119824, 48.8567, 2.3508, 'M');
NumberFormat df = DecimalFormat.getInstance();
df.setMaximumFractionDigits(3);
df.setRoundingMode(RoundingMode.CEILING);
System.out.println(df.format(distance) + " Miles\n"); //displays 213.471 Miles
haversine([-0.116773, 51.510357], [-77.009003, 38.889931])
var haversine = require('haversine-distance')
var a = { lat: 37.8136, lng: 144.9631 }
var b = { lat: 33.8650, lon: 151.2094 }
// 714504.18 (in meters)
console.log(haversine(a, b))
options.unit
- Unit of measurement applied to result (defaultkm
, availablekm, mile, meter, nmi
)options.threshold
- If passed, will result in library returningboolean
value of whether or not the start and end points are within that supplied threshold. (defaultnull
)options.format
- The format of start and end coordinate arguments. See table below for available values. (defaultnull
)
const haversine = require('haversine')
const start = {
latitude: 30.849635,
longitude: -83.24559
}
const end = {
latitude: 27.950575,
longitude: -82.457178
}
console.log(haversine(start, end))
console.log(haversine(start, end, {unit: 'mile'}))
console.log(haversine(start, end, {unit: 'meter'}))
console.log(haversine(start, end, {threshold: 1}))
console.log(haversine(start, end, {threshold: 1, unit: 'mile'}))
console.log(haversine(start, end, {threshold: 1, unit: 'meter'}))