谷歌地图方向 mvcobject 获得单独的步骤

Google Maps directions mvcobject getting a individual step

本文关键字:单独 方向 mvcobject 谷歌地图      更新时间:2023-09-26

我正在使用directionsService通过google maps javascript api获取路线。问题是我想获取单个步骤,但将它们作为 mvc 对象的一部分,因此当您单击它们时,它们会在地图上呈现为默认值

directionsDisplay.setDirections(response); 

确实如此。一些代码:

var directionsService = new google.maps.DirectionsService();
directionsDisplay.setMap(map);
var request = {
        origin : a,
        destination : b,
        travelMode : google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
    if (status == google.maps.DirectionsStatus.OK) {
                directionsDisplay.setDirections(response);
          //Instead of setting directions to a panel i want to 
          //set just one to a panel and yet have it link to the
          //map like the above does.
            }});

这个想法是你必须迭代路线的每一条路,然后遍历这条路的每一步,并渲染你自己的HTML来表示它。请参阅以下代码(假设您定义了 mapdirectionsDisplaydirectionsService 以及request):

directionsService.route(request, function(response, status) {
  // Make sure the directions request was valid
  if (status == google.maps.DirectionsStatus.OK) {
    // Give the response to the directions display
    directionsDisplay.setDirections(response);
    // Display the route on the map
    directionsDisplay.setMap(map);
    // Grab the result from the routes
    var routeResult = response.routes[0];
    // Iterate over each leg of the route
    routeResult.legs.forEach(function(leg) {
      // Build HTML for each step
      var stepHTML = '';
      leg.steps.forEach(function(step) {
        stepHTML += '<div class="directionStep">'+
                  '<div>'+step.instructions+'</div>'+
                  '<div class="grey">'+step.distance.text+' ('+step.duration.text+')'+'</div>'+
                '</div>';
      });
      // Put the step HTML somewhere
      $('.steps').append(stepHTML);
    });
  }
});

然后,聆听各个步骤的点击,并做任何您需要的响应。