Calculating Distance in Miles from Latitude and Longitude
By Pete Freitag
The amount of data out there via API's is increadible these days. For instance you can take an address, and get the latitude and longitude using Google's GeoCoding API.
I am using this API along with some others to build a pretty some interesting stuff (more on that when its public).
Today I needed to calculate the distance between two points, I found a bunch of formulas here (link removed, no longer working) to convert two lats and longs into miles. They had some more complicated formulas, but I went with an easier one because approximate accuracy was sufficient. Here's how the formula translated into SQL (tested on MySQL):
SELECT id, place_name, ROUND( SQRT( POW((69.1 * (#Val(arguments.latitude)# - latitude)), 2) + POW((53 * (#Val(arguments.longitude)# - longitude)), 2)), 1) AS distance FROM places ORDER BY distance ASC
I am also rounding it to one decimal place, which you can remove if you want.
Speaking of mileage, if you are looking for a Web Application to track business mileage checkout mileagepad.com
Calculating Distance in Miles from Latitude and Longitude was first published on January 18, 2007.
If you like reading about maps, latitude, longitude, geo, gps, geocoding, sql, mysql, or google then you might also like:
- Google's JavaScript API Loader
- Cheat Sheet Roundup - Over 30 Cheatsheets for developers
- Order by NULL Values in MySQL, Postgresql and SQL Server
- Top 10 Reserved SQL Keywords
Discuss / Follow me on Twitter ↯
Tweet Follow @pfreitagComments
(Greets to bazmod!)
I built WalkJogRun.net with ColdFusion and MySql and have tons of Geo-related stuff if you need anything. The JavaScript does a lot of the Google Maps API stuff but there is some CF and MySql code I can share.
if you remember that the lines are drawn on a globe, you'll realise 69.1 is only correct at two exact latitudes, north and south of the equator.