Home>Article>Backend Development> PHP calculates the distance between two points on the earth (detailed example)

PHP calculates the distance between two points on the earth (detailed example)

藏色散人
藏色散人 Original
2019-04-03 13:12:57 5024browse

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.

PHP calculates the distance between two points on the earth (detailed example)

This problem can be solved using thehaversine 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:


      

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn