获取或填充自定义变量与谷歌地图方向的响应

Get or populate custom variable with response from google maps directions

本文关键字:谷歌地图 方向 响应 变量 填充 自定义 获取      更新时间:2023-09-26

我有这个函数,我需要用响应填充结果变量。我在谷歌上搜索了几个小时,但很不幸。问题有可能吗?

function getRoute() {
   var result; // array or object
   directionsService.route(request, function(response, status) {
      if (status == google.maps.DirectionsStatus.OK) {
         directionsRenderer.setDirections(response);
         console.log(response.routes[0].legs[0].distance.text);
         console.log(response.routes[0].legs[0].duration.text);
      }
   });
   return result;
}

结果作为数组或对象返回

var result = getRoute();
    console.log(result);  // anything like {'direction': 0, 'distance': 0}

感谢您的建议或想法

方向服务是异步的,它不能返回数据。如果需要使用结果,请在回调函数中使用它。如果以后需要它,可以将其分配给全局变量(或将其存储在隐藏的输入字段中)。