I grabbed a database of the zip codes and their langitudes/latitudes, etc from this This page. It has got the following fields:
ZIP, LATITUDE, LONGITUDE, CITY, STATE, COUNTY, ZIP_CLASS
The data was in a text file but I inserted it into a MySQL table. My question now is, how can i utilise the fields above to calculate the distance between two zip codes that a user can enter on the website? Working code in PHP will be appreciated
In your zip table you need to grab the coordinates (lat,long) for the two points for which you want to get the distance.
You can then either calculate the distance right in the SQL or with PHP. Both methods are outlined in this post:
http://dev.strategystar.net/2011/10/mysql-php-get-distance-between-two-coordinates-in-miles-kilometers/
The calculation in the example is based on the formula already discussed in this thread. It provides the radius for the earth in both miles and kilometers so it will allow you to get the distance between two points in both units.
The link above is great because the method for calculation does not include any magic numbers, just the radius of the earth!
You can also try hitting a web service to calc the distance. Let someone else do the heavy lifting.
https://www.zipcodeapi.com/API#distance
This is mike's answer with some annotations for the magic numbers. It seemed to work fine for me for some test data:
It can be done with just maths...
Check out the Haversine formula for calculating great circle distances between two points. Some more samples can be found here
Haversine formula:
(Note that angles need to be in radians to pass to trig functions).