Retrieving coordinates of two addresses using Google Maps and calculating distance

So here’s a quick couple snippets of code that will allow you to retrieve the coordinates of two locations using Google Maps API — no API key necessary.

This first function will return the coordinates of specific address (I find pretty much anything works, whether it’s a full address with street number, or just a postal code, or simply a city name) as an array of coordinates:

function getCoordinates($address) {
  $url = "http://maps.google.com/maps/geo?q=" . urlencode($address)
         . "&output=json";
  $result = file_get_contents($url);
  $result = json_decode($result, 1);
  if (isset($result['Placemark'])) {
    list($lat, $long) = $result['Placemark'][0]['Point']['coordinates'];
  } else {
    $lat = $long = false;
  }
  return array($lat, $long);
}

and the following function will accept the lat/long coordinates of two separate points and return their distance (not road/traveling distance, but straight-shot distance) in KM:

function calculateDistance($lat1, $long1, $lat2, $long2) {
  $R = 6371; // earth's mean radius in km
  $dLat = deg2rad($lat2-$lat1);
  $dLon = deg2rad($long2-$long1);
  $lat1 = deg2rad($lat1);
  $lat2 = deg2rad($lat2);

  $a = sin($dLat/2) * sin($dLat/2) +
      cos($lat1) * cos($lat2) *
      sin($dLon/2) * sin($dLon/2);
  $c = 2 * atan2(sqrt($a), sqrt(1-$a));
  $d = $R * $c;

  // return distance in KM
  return $d;
}

Now it certainly may be worthwhile to cache coordinates for a given location, depending on your usage, because retrieving the coordinates from Google for a large quantity of addresses at once can take some time.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>