Distance calculation from latitude and longitude in PHP

geographical distance calculationGeographical distance calculation is a common cause of headaches. Indeed, if the earth were flat, you could simply use Pythagoras’ theorem, which states that in a right triangle, the square of the hypotenuse (the side opposite the right angle) is equal to the sum of the squares of the other two sides (you probably remember its formula a2 + b2 = c2 from high school). But of course, the Earth is not flat…

In the following distance calculation function, I use the haversine formula to calculate the distance between two points on the Earth’s surface, feeding it the latitude and longitude of both points.

The calculation is a bit tricky, so I won’t describe it in details (check the haversine formula article on Wikipedia for more details). Rather, let me just give you a very general description of the function:

  • Using the Haversine formula, we calculate the distance in degrees between the two sets of coordinates
  • The value in degrees is converted to kilometers (by default), miles or nautical miles, depending on your needs.
  • The distance is returned, with the chosen precision (2 decimals by default).

Keep in mind that since the Earth is not a perfect sphere, there is a little margin of error associated to the haversine formula.

Here is an example of how to use that function, taking coordinates from our worldCities database.

For more details about the difficulties of distance calculation, check the Wikipedia article on geographical distance, in which a few other formulas are mentioned, some more accurate for long distances and others for short distances.

3 thoughts on “Distance calculation from latitude and longitude in PHP

Leave a comment