Calculation Method of Geographical Coordinate Distance between php Two Points
- 2021-11-13 06:49:03
- OfStack
In this paper, we share the specific code of php to calculate the distance between two geographical coordinates for your reference. The specific contents are as follows
Function: Calculate the spherical distance between two points according to the pi and the radius coefficient of the earth and the latitude and longitude of the coordinates of two points.
Get the coordinate distance between two points:
<?php
/**
* Calculate the distance between two geographical coordinates
* @param Decimal $longitude1 Starting point longitude
* @param Decimal $latitude1 Starting point latitude
* @param Decimal $longitude2 End longitude
* @param Decimal $latitude2 Terminal latitude
* @param Int $unit Unit 1: Rice 2: Kilometres
* @param Int $decimal Precision Retain decimal places
* @return Decimal
*/
function getDistance($longitude1, $latitude1, $longitude2, $latitude2, $unit=2, $decimal=2){
$EARTH_RADIUS = 6370.996; // Earth radius coefficient
$PI = 3.1415926;
$radLat1 = $latitude1 * $PI / 180.0;
$radLat2 = $latitude2 * $PI / 180.0;
$radLng1 = $longitude1 * $PI / 180.0;
$radLng2 = $longitude2 * $PI /180.0;
$a = $radLat1 - $radLat2;
$b = $radLng1 - $radLng2;
$distance = 2 * asin(sqrt(pow(sin($a/2),2) + cos($radLat1) * cos($radLat2) * pow(sin($b/2),2)));
$distance = $distance * $EARTH_RADIUS * 1000;
if($unit==2){
$distance = $distance / 1000;
}
return round($distance, $decimal);
}
// Starting point coordinates
$longitude1 = 113.330405;
$latitude1 = 23.147255;
// End point coordinates
$longitude2 = 113.314271;
$latitude2 = 23.1323;
$distance = getDistance($longitude1, $latitude1, $longitude2, $latitude2, 1);
echo $distance.'m'; // 2342.38m
$distance = getDistance($longitude1, $latitude1, $longitude2, $latitude2, 2);
echo $distance.'km'; // 2.34km
?>