Given longitude and latitude, find the distance between two points on the earth. First we need to understand the solution to the problem, and then use PHP code to implement the calculation.
This problem can be solved using the haversine formula
:
The great circle distance or orthogonal distance is a sphere (or The shortest distance between two points on the Earth's surface. In order to use this method, we need the coordinates of point A and point B. The great circle method is superior to other methods.
First, convert the latitude and longitude values from decimal degrees to radians. Therefore, divide both the longitude and latitude values by 180/pi. The value of pi is 22/7. The value of 180/pi is approximately 57.29577951. If we want to calculate the distance between two places in miles, we use 3,963, which is the radius of the Earth. If we want to calculate the distance between two places in kilometers, we use 6,378.8, which is the radius of the Earth.
求纬度值(以弧度为单位): 纬度值,单位为弧度,lat =纬度/ (180/pi) 或 纬度值,以弧度为单位,lat =纬度/ 57.29577951 求经度的弧度值: 经度值,单位为弧度,long =经度/ (180/pi) 或 经度值,单位为弧度,long =经度/ 57.29577951
Find the latitude and longitude coordinates of point A. Convert latitude and longitude values to radians using the conversion method above. I call it lat1 and long1. Do the same process for the coordinates of point B to get lat2 and long2.
Now, to get the distance between point A and point B, use the following formula:
距离,d = 3963.0 * arccos[(sin(lat1) * sin(lat2)) + cos(lat1) * cos(lat2) * cos(long2 - long1)]
The unit of the obtained distance d is miles. If you want your values to be in kilometers, multiply d by 1.609344.
d(千米)= 1.609344 * d(英里)
Therefore, you can use the great circle distance method to get the shortest distance between two places on the earth.
The implementation code for PHP to calculate the distance between two points on the earth is as follows:
<?php function twopoints_on_earth($latitudeFrom, $longitudeFrom, $latitudeTo, $longitudeTo) { $long1 = deg2rad($longitudeFrom); $long2 = deg2rad($longitudeTo); $lat1 = deg2rad($latitudeFrom); $lat2 = deg2rad($latitudeTo); $dlong = $long2 - $long1; $dlati = $lat2 - $lat1; $val = pow(sin($dlati/2),2)+cos($lat1)*cos($lat2)*pow(sin($dlong/2),2); $res = 2 * asin(sqrt($val)); $radius = 3958.756; return ($res*$radius); } //经纬度两点 $latitudeFrom = 19.017656 ; $longitudeFrom = 72.856178; $latitudeTo = 40.7127; $longitudeTo = -74.0059; // 孟买和纽约之间的距离 print_r(twopoints_on_earth( $latitudeFrom, $longitudeFrom, $latitudeTo, $longitudeTo).' '.'miles');
Output:
2.0043678382716137 K.M
This article This is an introduction to the method of calculating the distance between two points on the earth in PHP. I hope it will be helpful to friends who need it!
The above is the detailed content of PHP calculates the distance between two points on the earth (detailed example). For more information, please follow other related articles on the PHP Chinese website!