2012-06-14 38 views
2

我正在使用directionsService通過google maps javascript api獲取路線。問題是,我想各個步驟,但讓他們成爲MVC對象的一部分,所以當你點擊他們,他們呈現在地圖上作爲默認Google Maps directions mvcobject獲取一個單獨的步驟

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. 
      }}); 

回答

0

的想法是,你必須遍歷該路線的每一條腿,然後在腿部的每一步,並使得自己的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); 
    }); 
    } 
}); 

然後,聽取各個步驟點擊,做任何你需要的響應。

相關問題