Calculating Distance in Miles from Latitude and Longitude
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 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 sufficent. 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
- Cheat Sheet Roundup - Over 30 Cheatsheets for developers - September 1, 2005
- Top 10 Reserved SQL Keywords - October 28, 2008
- INFORMATION_SCHEMA Support in MySQL, PostgreSQL - February 18, 2008
- Backwards LIKE Statements - January 10, 2007
# Your lat/long of preferences
SET @arguments_latitude = 51.355887;
SET @arguments_longitude = -2.949691;
# Make a distance query
POW((69.1 * (@arguments_latitude - p.latitude)), 2) +
POW((53 * (@arguments_longitude - p.longitude)), 2)
, 1) AS distance
FROM postcodes p
ORDER BY distance DESC;
- Docker Container exited with code 137
- Why is my cron.daily script not running?
- Announcing FuseGuard Version 3
- CFSummit 2017
- Java Unlimited Strength Crypto Policy for Java 9 or 1.8.0_151
- Java 9 Security Enhancements
- Upcoming CFML Conferences in April 2017
- CFSummit 2016 Slides