dphdh395195
dphdh395195
2014-08-27 15:52

使用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>');  
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • dttwois6098 dttwois6098 7年前

    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);
    
    点赞 评论 复制链接分享

相关推荐