如何使用 Google 距离矩阵获取两个位置之间的距离

How to get distance between two locations using Google Distance Matrix

<html>
    <body>

        <form action="" method="post">

            <label>Origin:</label> <input type="text" name="o" placeholder="Enter Origin location" required> <br><br>
            <label>Destination:</label> <input type="text" name="d" placeholder="Enter Destination location" required> <br><br>
            <input type="submit" value="Calculate distance & time" name="submit"> <br><br>

        </form>

        <?php
        $con = mysqli_connect("localhost","root","","buspass");

            if(isset($_POST['submit'])){
            $origin = $_POST['o']; 
            $destination = $_POST['d'];
            $api = file_get_contents("https://www.google.com/maps/search/?api=1&query=centurylink+field/distancematrix/json?units=imperial&origins=".$origin."&destinations=".$destination."&key=AIzaSyAWOoVKOdZ3xCEvoz735TBrggU0q7EgPsU");
            $data = json_decode($api);
        ?>
                <label><b>Distance: </b></label> <span>
                <?php 
                if (is_object($data)) {
                    echo((int)$data->rows[0]->elements[0]->distance->value / 1000).' Km'; //line24
                }
                ?>
                </span> <br><br>
            <label><b>Travel Time: </b></label> <span>
            <?php
            if (is_object($data)) {
                echo $data->rows[0]->elements[0]->duration->text;        //line 31
            }
            ?>
            </span> 
    
        <?php 
        } 
        ?>

    </body>
</html>

当我输入这两个位置时 POST 它应该输出这两个位置之间的距离和到达的大概时间

错误信息

Notice: Trying to get property 'rows' of non-object in C:\xampp\htdocs\Bus Pass\distance.php on line 24

Notice: Trying to get property 'elements' of non-object in C:\xampp\htdocs\Bus Pass\distance.php on line 24

Notice: Trying to get property 'distance' of non-object in C:\xampp\htdocs\Bus Pass\distance.php on line 24

Notice: Trying to get property 'value' of non-object in C:\xampp\htdocs\Bus Pass\distance.php on line 24 0 Km

Travel Time: Notice: Trying to get property 'rows' of non-object in C:\xampp\htdocs\Bus Pass\distance.php on line 31

Notice: Trying to get property 'elements' of non-object in C:\xampp\htdocs\Bus Pass\distance.php on line 31

Notice: Trying to get property 'duration' of non-object in C:\xampp\htdocs\Bus Pass\distance.php on line 31

Notice: Trying to get property 'text' of non-object in C:\xampp\htdocs\Bus Pass\distance.php on line 31

我自己遇到了 PHP 的 JSON 对象,

1。将 $data = json_decode($api); 替换为 $data = json_decode($api, true); 以获得关联数组。

2。删除所有对象检查(如 if (is_object($data)) {)。

3。最后,使用数组样式调用而不是对象样式,例如,将代码更改为:

$data->rows[0]->elements[0]->distance->value

变成类似这样的东西:

$data['rows'][0]['elements'][0]['distance']['value']