-3

为什么我的代码不显示距离和持续时间?

这是我的代码(html + js):

<!DOCTYPE html>
<html>
   <head>
      <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
      <meta charset="utf-8" />
      <title>Google</title>
      <script src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
      <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>
      <style type="text/css">
         #result{
         width: 300px;
         height: 400px;
         background-color: red;
         }
      </style>

      <script>
         var service = new google.maps.DistanceMatrixService();
         service.getDistanceMatrix(
         {
         origins: ["Berlin"],
         destinations: ["Frankfurt"],
         travelMode: google.maps.TravelMode.DRIVING,
         }, callback);

         function callback(response, status) {
         $("#result").text(response.rows[0].elements.distance.text + " and " + response.rows[0].elements.duration.text);
         }
      </script>
   </head>

   <body>
      <div id="result"></div>
   </body>
</html>

这是示例 JSON 输出:

http://maps.googleapis.com/maps/api/distancematrix/json?origins=Berlin&destinations=Frankfurt&mode=driving&language=de-DE&sensor=false

4

1 回答 1

2

elements也是一个数组,因此您的回调函数必须如下所示:

 function callback(response, status) {
     $("#result").text(response.rows[0].elements[0].distance.text + " and " + response.rows[0].elements[0].duration.text);
 }

这是一个工作 JSfiddle

提示:使用 Javascript 控制台查看 Javascript 中的错误。

于 2012-10-30T08:44:19.250 回答