brasofilo

SO-25531700

Aug 29th, 2014
363
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <?php
  2. /**
  3. * Run this as http://example.com/test.php
  4. */
  5.  
  6. function do_it( $where ) {
  7.     $params = array(
  8.         'origin'        => 'New York, NY',
  9.         'destination'   => $where,
  10.         'sensor'        => 'true',
  11.         'units'         => 'metric'
  12.     );
  13.  
  14.     // Join parameters into URL string
  15.     foreach($params as $var => $val){
  16.         $params_string .= '&' . $var . '=' . urlencode($val);  
  17.     }
  18.  
  19.     // Request URL
  20.     $url = "http://maps.googleapis.com/maps/api/directions/json?".ltrim($params_string, '&');
  21.  
  22.     // Make our API request
  23.     $curl = curl_init();
  24.     curl_setopt($curl, CURLOPT_URL, $url);
  25.     curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
  26.     $return = curl_exec($curl);
  27.     curl_close($curl);
  28.  
  29.     // Parse the JSON response
  30.     $directions = json_decode($return);
  31.  
  32.     // Print distance
  33.     printf(
  34.         '<p><strong>Distance from %s: </strong>%s</p>',
  35.         $where,
  36.         $directions->routes[0]->legs[0]->distance->text
  37.     );  
  38. }
  39.  
  40. do_it( 'Manchester, NH' );
  41. do_it( 'Philadelphia, NJ' );
RAW Paste Data