RBA Cash Rate: 4.35% · 1AUD = 0.67 USD · Inflation: 4.1%  
Leading Digital Marketing Experts | 1300 235 433 | Aggregation Enquires Welcome | Book Appointment
Example Interest Rates: Home Loan Variable: 5.20% (5.24%*) • Home Loan Fixed: 5.48% (6.24%*) • Fixed: 5.48% (6.24%*) • Variable: 5.20% (5.24%*) • Investment IO: 5.78% (6.81%*) • Investment PI: 5.49% (6.32%*)

Calculate The Distance Between Two Geographical Points With PHP

Calculate The Distance Between Two Geographical Points With PHP

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

1
<?php 
2
/*
3
 Calculate The Distance Between Two Geographical Points With PHP
4
 http://www.beliefmedia.com/calculate-distance-php
5
*/
6
 
7
function beliefmedia_distance($lat1, $lon1, $lat2, $lon2, $unit = 'm', $round = 2) {
8
 
9
  $theta = $lon1 - $lon2;
10
  $dist = rad2deg(acos(sin(deg2rad($lat1)) * sin(deg2rad($lat2)) + cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta))));
11
  $miles = $dist * 60 * 1.1515;
12
 
13
  switch ($unit) {
14
      case 'k':
15
          return round(($miles * 1.609344), $round);
16
          break;
17
      case 'n':
18
          return round(($miles * 0.8684), $round);
19
          break;
20
      default:
21
          return round($miles, $round);
22
          break;
23
  }
24
}
25
?>

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.

1
/* Miles */
2
echo beliefmedia_distance(32.9697, -96.80322, 29.46786, -98.53506, 'm') . ' miles<br>';
3
 
4
/* Kilometers */
5
echo beliefmedia_distance(32.9697, -96.80322, 29.46786, -98.53506, 'k') . ' kilometers<br>';
6
 
7
/* Nautical miles */
8
echo beliefmedia_distance(32.9697, -96.80322, 29.46786, -98.53506, 'n') . ' nautical miles<br>';

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 .

1
<?php 
2
/*
3
 Return Latitude and Longitude with Physical Address
4
 https://developers.google.com/maps/documentation/geocoding/intro
5
 Reuires Google Maps API KEY
6
 See Google's Data: echo 'pre' . print_r($data, true) . '/pre';
7
*/
8
 
9
function beliefmedia_reverse_coordinates($address, $key = '') {
10
 
11
  $data = file_get_contents('https://maps.googleapis.com/maps/api/geocode/json?address=' . rawurlencode($address) . '&key=' . $key);
12
  $data = json_decode($data, true);
13
 
14
  /* Retured array */
15
  if ($data['status'] == 'OK') {
16
 
17
    $coords = array();
18
    $coords['lat'] = $data['results']['0']['geometry']['location']['lat'];
19
    $coords['lng'] = $data['results']['0']['geometry']['location']['lng'];
20
 
21
    return (array) $coords;
22
 
23
  } else {
24
 
25
    return false;
26
 
27
 }
28
}
29
 
30
/* Usage */
31
$address = '6 Cavendish St, Concord West, NSW, 2138';
32
echo 'pre' . print_r(beliefmedia_reverse_coordinates($address), true) . '/pre';
33
?>

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.

1
<?php 
2
/*
3
 Return Latitude and Longitude with Physical Address (caching data)
4
 Requires 'Simple Cache With PHP' http://shor.tt/1P7C
5
 https://developers.google.com/maps/documentation/geocoding/intro
6
 Requires Google Maps API KEY
7
 See Google's Data: echo 'pre' . print_r($data, true) . '/pre';
8
*/
9
 
10
function beliefmedia_reverse_coordinates($address, $key = '') {
11
 
12
  $transient = 'geoaddress_' . md5($address);
13
  $cachedresult = beliefmedia_get_transient_data($transient);
14
 
15
  if ($cachedresult !== false ) {
16
   return $cachedresult;
17
 
18
  } else {
19
 
20
   $data = file_get_contents('https://maps.googleapis.com/maps/api/geocode/json?address=' . rawurlencode($address) . '&key=' . $key);
21
   $data = json_decode($data, true);
22
 
23
    /* Retured array */
24
    if ($data['status'] == 'OK') {
25
 
26
      $coords = array();
27
      $coords['lat'] = $data['results']['0']['geometry']['location']['lat'];
28
      $coords['lng'] = $data['results']['0']['geometry']['location']['lng'];
29
      beliefmedia_set_transient($transient, $coords);
30
      return $coords;
31
 
32
    } else {
33
      return false;
34
    }
35
 
36
 }
37
}
38
 
39
/* Usage */
40
$address = '6 Cavendish St, Concord West, NSW, 2138';
41
echo 'pre' . print_r(beliefmedia_reverse_coordinates($address), true) . '/pre';
42
?>

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

Download our 650-page guide on Finance Marketing. We'll show you exactly how we generate Billions in volume for our clients.

  E. Australia Standard Time [ UTC+10, Default ] [ CHECK TO CHANGE ]

  Want to have a chat?
 

RELATED READING

Like this article?

Share on Facebook
Share on Twitter
Share on Linkdin
Share on Pinterest

Leave a comment