title: Get driving distance between two points using Google Maps API
body: <p>I'm trying to get <strong>driving</strong> distance between two points using Google Maps API. Now, I have code which get direct distance:</p>
  
  <p>This function get lat and lng:</p>
  
  <pre><code>function get_coordinates($city, $street, $province)
  {
      $address = urlencode($city.','.$street.','.$province);
      $url = "http://maps.google.com/maps/api/geocode/json?address=$address&amp;sensor=false&amp;region=Poland";
      $ch = curl_init();
      curl_setopt($ch, CURLOPT_URL, $url);
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
      curl_setopt($ch, CURLOPT_PROXYPORT, 3128);
      curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
      curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
      $response = curl_exec($ch);
      curl_close($ch);
      $response_a = json_decode($response);
      $return = array('lat' =&gt; $response_a-&gt;results[0]-&gt;geometry-&gt;location-&gt;lat, 'long' =&gt; $long = $response_a-&gt;results[0]-&gt;geometry-&gt;location-&gt;lng);
  
      return $return;
  }
  </code></pre>
  
  <p>This function calculate distance between two points based on lat &amp; lng:</p>
  
  <pre><code>function getDistanceBetweenPoints($lat1, $lon1, $lat2, $lon2) {
      $theta = $lon1 - $lon2;
      $miles = (sin(deg2rad($lat1)) * sin(deg2rad($lat2))) + (cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta)));
      $miles = acos($miles);
      $miles = rad2deg($miles);
      $miles = $miles * 60 * 1.1515;
      $kilometers = $miles * 1.609344;
      return $kilometers;
  }
  </code></pre>
  
  <p>This function print distance by kilometers:</p>
  
  <pre><code>function get_distance($lat1, $lat2, $long1, $long2)
  {
      /* These are two points in New York City */
      $point1 = array('lat' =&gt; $lat1, 'long' =&gt; $long1);
      $point2 = array('lat' =&gt; $lat2, 'long' =&gt; $long2);
  
      $distance = getDistanceBetweenPoints($point1['lat'], $point1['long'], $point2['lat'], $point2['long']);
      return $distance;
  }
  </code></pre>
  
  <p>Usage:</p>
  
  <pre><code>$coordinates1 = get_coordinates('Katowice', 'Korfantego', 'Katowicki');
  $coordinates2 = get_coordinates('Tychy', 'Jana Pawła II', 'Tyski');
  
  echo 'Distance: &lt;b&gt;'.round(get_distance($coordinates1['lat'], $coordinates2['lat'], $coordinates1['long'], $coordinates2['long']), 1).'&lt;/b&gt; km';
  </code></pre>
  
  <p>But this code get direct distance. I need driving distance. 
  How I can get driving distance using google maps API?</p>
  
  <p>Thanks for your help!</p>