# Calculating distance using lat/long PHP

Interested in calculating the distance between latitude and longitude using PHP or MySQL? After doing a bit of research on the web, I was able to find the PHP solution that I was looking for. At first I was looking at how to calculate the distance for between a latitude and longitude point mathematically, but then tried to find out if anyone else had a solution that implemented PHP or MySQL that I could reuse.

Have a look at the solution below and let me know if you have any questions.

PHP:``` function getDistanceBetweenPointsNew(\$latitude1, \$longitude1, \$latitude2, \$longitude2, \$unit = 'Mi') { \$theta = \$longitude1 - \$longitude2; \$distance = (sin(deg2rad(\$latitude1)) * sin(deg2rad(\$latitude2))) + (cos(deg2rad(\$latitude1)) * cos(deg2rad(\$latitude2)) * cos(deg2rad(\$theta))); \$distance = acos(\$distance); \$distance = rad2deg(\$distance); \$distance = \$distance * 60 * 1.1515; switch(\$unit) { case ‘Mi’: break; case ‘Km’ : \$distance = \$distance * 1.609344; }return (round(\$distance,2)); }```

MySQL:
``` \$qry = "SELECT *,(((acos(sin((".\$latitude."*pi()/180)) * sin((`Latitude`*pi()/180))+cos((".\$latitude."*pi()/180)) * cos((`Latitude`*pi()/180)) * cos(((".\$longitude."- `Longitude`)*pi()/180))))*180/pi())*60*1.1515) as distance FROM `MyTable` WHERE distance <= ".\$distance." ```

I would like to contribute this solution to the author of The marketing technology blog thanks!

## 4 thoughts on “Calculating distance using lat/long PHP”

1. Douglas Karr says:

Thanks for the kind mention!

2. Harry Hobson says:

Thanks so much for this!

3. Horace Woods says:

5ir2ujvm03iruo8n

4. cassandra says:

Great article thanks for sharing!