The following PHP function calculates the distance between two points based on longitude and latitude. As a former airline pilot by trade (that wrote numerous aviation applications), and now working with mapping on an almost daily basis for our clients, I've recycled these functions countless times.
The function, provided with the latitude and longitude of two points, will output a distance in either miles, kilometers, or nautical miles. Additional units of measurement can be added in if the defaults don't work for you.
Usage is simple and rather self explanatory based on the code below. South latitudes are negative and east longitudes are positive. The latitude and longitude are provided as decimal degrees.
Returning Coordinates of a Physical Address
The following function will return geographic latitude and longitude for a physical street address. Use requires that you have a Google Geocoding API key .
From Google: "Geocoding is a time and resource intensive task. Whenever possible, pre-geocode known addresses (using the Google Maps Geocoding API described here or another geocoding service), and store your results in a temporary cache of your own design". Using our Simple Cache code, we might cache returned data as follows.
beliefmedia_get_transient_data() function (rather than
beliefmedia_get_transient()) more closely resembles an option since it has no expiry time.
Note that you'll obviously be able to return Google's full data array or just your refined result; the choice is obviously yours.
- You might consider converting an IP to location, and then using that information for other purposes; for example, displaying a nearest shop location. In an upcoming post we'll provide example code (when published, you'll find it here.
- Google's Geocoding service requires an API Key. Get one here .
- Hashing an address for the purpose of caching it might prove problematic. To ensure consistency in how the cached data is named you will likely have to force certain fields in a form, and then cache down to the nearest suitable accuracy (i.e. exact, street address, or suburb).