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

时间:2012-10-30 08:32:43

标签: javascript html google-maps

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

这是我的代码(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

1 个答案:

答案 0 :(得分:2)

elements也是一个数组,所以你的回调函数必须如下所示:

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

这是working JSfiddle

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