简体   繁体   English

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

[英]Using Google Maps API to calculate distance between two addresses

Context: I can't disclose too much about the project since I'm under NDA. 背景信息:由于我属于NDA,因此我不能透露太多有关该项目的信息。

I am using this tutorial to calculate the distance between two addresses using Google Maps. 我正在使用本教程来使用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. 我希望输出的是定点的起始地址与目标地址之间的距离,该目标地址取决于用户在_ct_text_53ea3270e6e6d字段中输入的_ct_text_53ea3270e6e6d

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: 这是显示问题的屏幕截图:

在此处输入图片说明

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM