我正在尝试使用Google Maps API来计算两个点之间的时间和距离。我的代码相当简单并且可以工作(使用了键盘并且运行顺畅)但是当我部署代码并尝试使用该服务时,机器人给了我错误的答案...
这是代码:
$details = "http://maps.googleapis.com/maps/api/distancematrix/json?origins=Miami&destinations=Miami+Beach&mode=driving&sensor=false";
$json = file_get_contents($details);
$arr = json_decode($json, TRUE);
$distance = $arr[rows][0][elements][0][distance][text];
$time = $arr[rows][0][elements][0][duration][text];
$response = "You should be there in $time. Total distance you'll cover: $distance";
$parameters = array('chat_id' => $chatId, "text" => $response);
$parameters["method"] = "sendMessage";
echo json_encode($parameters);
这是机器人回答我的问题:
"You should be there in {. Total distance you'll cover: {";
这是实际的json:
{
"destination_addresses" : [ "Miami Beach, Florida, Stati Uniti" ],
"origin_addresses" : [ "Miami, Florida, Stati Uniti" ],
"rows" : [
{
"elements" : [
{
"distance" : {
"text" : "15,7 km",
"value" : 15745
},
"duration" : {
"text" : "22 min",
"value" : 1322
},
"status" : "OK"
}
]
}
],
"status" : "OK"
}
发生了什么事?!
更新:file_get_contents返回一个字符串。所以我将其解码为PHP数组,但现在机器人甚至没有回答!
答案 0 :(得分:0)
$details = "http://maps.googleapis.com/maps/api/distancematrix/json?origins=Miami&destinations=Miami+Beach&mode=driving&sensor=false";
$json = file_get_contents($details);
$JsonObject = json_decode($json);
$distance = $JsonObject->rows[0]->elements[0]->distance->text;
$time = $JsonObject->rows[0]->elements[0]->duration->text;
$response = "You should be there in $time. Total distance you'll cover: $distance";
$chatId = "your telegram id here";
$botToken = "your bot token here";
file_get_contents("https://api.telegram.org/bot$botToken/sendMessage?chat_id=$chatId&text=$response");
这个适用于file_get_contents。