Calculate all the points distance (Geolocation) in Km

Thu Jun 29 2023 08:43:39 GMT+0000 (Coordinated Universal Time)

Saved by @edsonjorgef1 #php

```<?php
// Enter your code here, enjoy!
// function calculateDistance(\$lat1, \$lon1, \$lat2, \$lon2) {
//     // approximate radius of Earth in km
//     \$R = 6371.0;

//     // convert degrees to radians

//     // calculate the differences in latitude and longitude
//     \$dlat = \$lat2 - \$lat1;
//     \$dlon = \$lon2 - \$lon1;

//     // apply the Haversine formula
//     \$a = sin(\$dlat / 2) ** 2 + cos(\$lat1) * cos(\$lat2) * sin(\$dlon / 2) ** 2;
//     \$c = 2 * atan2(sqrt(\$a), sqrt(1 - \$a));

//     // calculate the distance
//     \$distance = \$R * \$c;

//     return \$distance;
// }

// // Array of coordinates
// \$coordinates = array(
//     array(-14.537804, 40.672439, "NA1"),  // NA1
//     array(-14.532698, 40.674953, "NA2"),  // NA2
//     array(-14.529319, 40.675874, "NA3"),  // NA3
//     array(-14.523059, 40.675931, "NA4"),  // NA4
//     array(-14.459071, 40.674796, "NB5"),  // NB5
//     array(-14.460408, 40.678548, "NB6"),  // NB6
//     array(-14.461540, 40.680757, "NB7")   // NB7
// );

// // Calculate distances between points
// \$pointCount = count(\$coordinates);
// for (\$i = 0; \$i < \$pointCount - 1; \$i++) {
//     \$coord1 = \$coordinates[\$i];
//     \$coord2 = \$coordinates[\$i + 1];

//     \$j = \$i + 1;

//     \$lat1 = \$coord1[0];
//     \$lon1 = \$coord1[1];
//     \$lat2 = \$coord2[0];
//     \$lon2 = \$coord2[1];

//     \$distance = calculateDistance(\$lat1, \$lon1, \$lat2, \$lon2);
//     echo "Distance between point {\$coord1[2]} and point {\$coord2[2]}: {\$distance} km\n";
// }

function calculateDistance(\$lat1, \$lon1, \$lat2, \$lon2) {
// approximate radius of Earth in km
\$R = 6371.0;

// calculate the differences in latitude and longitude
\$dlat = \$lat2 - \$lat1;
\$dlon = \$lon2 - \$lon1;

// apply the Haversine formula
\$a = sin(\$dlat / 2) ** 2 + cos(\$lat1) * cos(\$lat2) * sin(\$dlon / 2) ** 2;
\$c = 2 * atan2(sqrt(\$a), sqrt(1 - \$a));

// calculate the distance
\$distance = \$R * \$c;

return \$distance;
}

// Array of coordinates
\$coordinates = array(
array(-14.537804, 40.672439, 'NA1'),
array(-14.532698, 40.674953, 'NA2'),
array(-14.529319, 40.675874, 'NA3'),
array(-14.523059, 40.675931, 'NA4'),
array(-14.459071, 40.674796, 'NB5'),
array(-14.460408, 40.678548, 'NB6'),
array(-14.461540, 40.680757, 'NB7')
);

// Calculate distances between each point
\$pointCount = count(\$coordinates);
for (\$i = 0; \$i < \$pointCount - 1; \$i++) {
\$coord1 = \$coordinates[\$i];
\$lat1 = \$coord1[0];
\$lon1 = \$coord1[1];

for (\$j = \$i + 1; \$j < \$pointCount; \$j++) {
\$coord2 = \$coordinates[\$j];
\$lat2 = \$coord2[0];
\$lon2 = \$coord2[1];

\$distance = calculateDistance(\$lat1, \$lon1, \$lat2, \$lon2);
echo "Distance between point {\$coord1[2]} and point {\$coord2[2]}: {\$distance} km\n";
}
}

```
content_copyCOPY