Skip to content
Advertisement

Haversine formula with php

I want to use this formula with php. I have a database with some values of latitute and longitude saved.

I want to find, with a certain value of latitude and longitude in input, all the distances (in km) from this point with each point in the database. To do this, I used the formula on googlemaps api:

JavaScript

Of course using that in php I replaced radians with deg2rad.The values 37,-122 are my values of input and lat,lng are my values in the database.

Below there is my code. The problem is that there is something wrong but I don’t understand what. The value of distance is of course wrong.

JavaScript

For values for example: $lat= 41.9133741000 $lng= 12.5203944000

I have the output of distance=”4826.9341106926″

Advertisement

Answer

The formula you used, seems to be the arccosine instead of the haversine formula. The haversine formula is indeed more appropriate to calculate the distance on a sphere, because it is less prone to rounding errors.

JavaScript

P.S. I couldn’t find an error in your code, so is it just a typo that you wrote $lat= 41.9133741000 $lat= 12.5203944000 ? Maybe you just calculated with $lat=12.5203944000 and $long=0 because you overwrote your $lat variable.

Edit:

Tested the code and it returned a correct result:

JavaScript
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement