Обалденная штука, и весьма сложная. Чтобы не ковыряться долго вот пару формул на php и javascript. Округление в км. Но не проблема поправить на метры. Видео с тестом на javascript, четенькое вычисление в метрах:
PHP код:
function getDistanceBetweenPointsNew($latitude1, $longitude1, $latitude2, $longitude2, $unit = 'miles') {
$theta = $longitude1 - $longitude2;
$distance = (sin(deg2rad($latitude1)) * sin(deg2rad($latitude2))) + (cos(deg2rad($latitude1)) * cos(deg2rad($latitude2)) * cos(deg2rad($theta)));
$distance = acos($distance);
$distance = rad2deg($distance);
$distance = $distance * 60 * 1.1515;
switch($unit) {
case 'miles':
break;
case 'kilometers' :
$distance = $distance * 1.609344;
}
return (round($distance,2));
}
Javascript код:
function getDistanceBetweenPoints(latitude1, longitude1, latitude2, longitude2, unit = 'miles') {
let theta = longitude1 - longitude2;
let distance = 60 * 1.1515 * (180/Math.PI) * Math.acos(
Math.sin(latitude1 * (Math.PI/180)) * Math.sin(latitude2 * (Math.PI/180)) +
Math.cos(latitude1 * (Math.PI/180)) * Math.cos(latitude2 * (Math.PI/180)) * Math.cos(theta * (Math.PI/180))
);
if (unit == 'miles') {
return Math.round(distance, 2);
} else if (unit == 'kilometers') {
return Math.round(distance * 1.609344, 2);
}
}
А вот кусочек кода для yandex maps api который юзется в видео выше
searchControl.search(text).then(function() {
searchControl.getResultsArray().forEach(el => {
let geo = [36.55472834448105,31.99336701599671];
let coord = el.geometry._coordinates;
let name = el.properties._data.name;
let distance = getDistanceBetweenPoints(geo[0], geo[1], coord[0], coord[1]);
console.log(text, distance + ' метров', name);
});
});