Google地图里程函数以返回两个地址之间的里程

问题描述 投票:-2回答:1

对于每个循环,退出工作。

public static function getMiles($to, $from)
{

    $from = urlencode($from);
    $to = urlencode($to);
    $data = file_get_contents("https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins=$from&destinations=$to&key=MyKey");

    $time = 0;
    $distance = 0;

    /* return as an object for easier notation */
    $json=json_decode( $data, false );
    $origins = $json->origin_addresses;
    $destinations=$json->destination_addresses;

    /*  if there are multiple rows, use a loop and `$rows[$i]` etc */
    $elements=$json->rows[0]->elements;

    foreach( $elements as $i => $obj ){
    } 
    //extract the mileage as meters
    $miles = $obj->distance->value;

    //converting the meters to miles
    $distance= round(($miles * '0.000621371192'), 1);
    //returning miles
    return $distance;

}

最终结果是返回2个地址之间的里程。错误消息是“'为foreach()提供了无效的参数'”。

php google-maps yii2 google-distancematrix-api
1个回答
0
投票

您的功能可以正常使用了。当我从距离矩阵API请求中混淆我的API密钥时,实际上我只会收到此“为foreach()提供了无效参数”错误。

尝试使用有效 API密钥(代替“ YOUR_KEY”)运行下面的代码:

function getMiles($to, $from)
{
    $from = urlencode($from);
    $to = urlencode($to);
    $data = file_get_contents("https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins=$from&destinations=$to&key=YOUR_KEY");

    $time = 0;
    $distance = 0;

    /* return as an object for easier notation */
    $json=json_decode( $data, false );
    $origins = $json->origin_addresses;
    $destinations=$json->destination_addresses;
    /*  if there are multiple rows, use a loop and `$rows[$i]` etc */
    $elements=$json->rows[0]->elements;

    foreach( $elements as $i => $obj ){
    } 
    //extract the mileage as meters
    $miles = $obj->distance->value;

    //converting the meters to miles
    $distance= round(($miles * '0.000621371192'), 1);
    //returning miles
    return $distance;
}

echo "\nMiles: " . getMiles("paris,france", "berlin,germany");

您获得的输出应该是Miles: 659

我建议您通过these guides仔细检查您的密钥,项目和计费帐户是否信誉良好。

希望这会有所帮助!

© www.soinside.com 2019 - 2024. All rights reserved.