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.
The Code
Usage
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 .
Caching Data
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.
Our 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.
Considerations
- 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).
Download
Title: Calculate Distance Between Two Geographical Points
Description: Calculate The Distance Between Two Geographical Points With PHP. Includes a version to cache data.
Download • Version 0.2, 2.3K, zip, Category: PHP Code & Snippets