使用Google Maps API计算两个地址之间的距离

问题描述:

Context: I can't disclose too much about the project since I'm under NDA.

I am using this tutorial to calculate the distance between two addresses using Google Maps.

I am looking to output the distance between the origin address, which is a fixed point, and the destination address, which is dependent on what the user inputs in the _ct_text_53ea3270e6e6d field.

It works fine pulling from one address, but if it pulls from multiple maps, it only shows the distance from one of the maps, not from each of them.

Here is a screenshot showing the problem:

enter image description here

Here is my code:

$field_value = do_shortcode('[ct id="_ct_text_53ea3270e6e6d" property="title | description | value"]'); 

// Our parameters
$params = array(
    'origin'        => '900 South Crouse Ave, Syracuse, NY, 13210',
    'destination'   => $field_value,
    'sensor'        => 'true',
    'units'         => 'imperial'
);

// Join parameters into URL string
foreach($params as $var => $val){
    $params_string .= '&' . $var . '=' . urlencode($val);  
}

// Request URL
$url = "http://maps.googleapis.com/maps/api/directions/json?".ltrim($params_string, '&');

// Make our API request
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$return = curl_exec($curl);
curl_close($curl);

// Parse the JSON response
$directions = json_decode($return);

// Print distance
 print('<p><strong>Distance from Campus: </strong>' .$directions->routes[0]->legs[0]->distance->text. '</p>');  

Had to replace this:

// Join parameters into URL string
foreach($params as $var => $val){
    $params_string .= '&' . $var . '=' . urlencode($val);
}

With:

$params_string = http_build_query($params);