如何在Google Directions API中修剪响应,隐藏路线首尾路段
Got it, let’s solve this without making a second API call—we can just tweak the response you already get to strip out those first and last legs linking to your base location. Here’s exactly how to do it:
First, make sure your initial API request asks for the full loop: set the origin and destination to your base location, and include your user-provided origin, waypoints, and destination as stopover waypoints in the request. That gives you the complete base -> origin -> waypoints -> destination -> base route in one response.
Then, once you get a successful response, we’ll slice off the first leg (base to origin) and last leg (destination to base) before passing the modified data to directionsDisplay. Here’s the updated code:
var directionsService = new google.maps.DirectionsService; var directionsDisplay = new google.maps.DirectionsRenderer; // Replace with your actual base address/coordinates var baseLocation = "YOUR_BASE_LOCATION"; var origin = document.getElementById('origin'); var waypoints = []; var waypointElements = document.getElementsByName('waypoints[]'); for(var i=0; i<waypointElements.length; i++) { waypoints.push({location: waypointElements[i].value, stopover:true}); } var destination = document.getElementById('destination'); // Request the full loop route directionsService.route({ origin: baseLocation, waypoints: [ {location: origin.value, stopover: true}, ...waypoints, {location: destination.value, stopover: true} ], destination: baseLocation, travelMode: 'DRIVING' }, function(response, status) { if(status === google.maps.DirectionsStatus.OK) { // Create a copy of the first route to avoid mutating the original response const modifiedRoute = {...response.routes[0]}; // Remove the first (base->origin) and last (destination->base) legs // slice(1, -1) keeps all elements except the first and last modifiedRoute.legs = modifiedRoute.legs.slice(1, -1); // Build a new response object with our trimmed route const modifiedResponse = {...response, routes: [modifiedRoute]}; // Pass the cleaned-up response to the display directionsDisplay.setDirections(modifiedResponse); } });
Quick Tips:
- How this works: The Directions API splits each stopover segment into a separate
legin theroutes[0].legsarray. Usingslice(1, -1)is a clean way to drop the first and last legs in one line. - Edge case protection: If you want to avoid errors if the route has fewer than 2 legs (unlikely here, but safe to add), throw in a quick check:
if (modifiedRoute.legs.length >= 2) { modifiedRoute.legs = modifiedRoute.legs.slice(1, -1); } - No extra API costs: We’re just manipulating existing response data, so you save on API quota and skip extra network latency.
内容的提问来源于stack exchange,提问作者sbrbot

