在Node.js中借助Google Directions Service API计算路线中点与交通时长中点
Great question! Let’s walk through how to solve this for your meeting scenario—finding the midpoint based on duration_in_traffic and pinpointing that location using the route’s polyline.
First, you’ll need more than just the total duration_in_traffic for the leg—you need to break down the route into individual steps (each step has its own traffic-adjusted duration). Here’s the step-by-step process:
- Define your target duration: Since you want the midpoint of the total traffic time, compute
target_duration = leg.duration_in_traffic.value / 2(use the numericvaluefield, which is in seconds, for precise calculations). - Iterate through route steps: Start accumulating the
duration_in_traffic.valueof each step until you hit the step where adding its duration would exceed your target. - Find the ratio within that step: Calculate how far into the target step you need to go with
step_ratio = (target_duration - accumulated_duration) / step.duration_in_traffic.value. This ratio (0 to 1) tells you what fraction of the step’s path corresponds to the midpoint time.
Google’s Directions API returns encoded polylines (the polyline.points field) to represent route paths. You’ll need to decode this string into a list of latitude/longitude coordinates, then find the exact point along the path using the ratio from step 1.
Decoding the Polyline
Most programming languages have libraries or built-in methods to decode Google’s polyline format:
- JavaScript: Use
google.maps.geometry.encoding.decodePath(polylineString)from the Google Maps JavaScript API’s geometry library. - Python: Use the
polylinepackage (install withpip install polyline) and callpolyline.decode(polylineString). - Other languages: You can implement Google’s published polyline decoding logic if no library exists for your stack.
Finding the Exact Meeting Point
Once you have the decoded coordinate array for the target step:
- Calculate the total length of the step’s path: Use a spherical distance calculator (like
google.maps.geometry.spherical.computeDistanceBetween()in JS, orgeopyin Python) to sum the distance between each consecutive pair of coordinates in the path. - Find the segment matching your ratio: Multiply the total path length by
step_ratioto get the target distance along the path. Then iterate through the path segments, accumulating distances until you find the segment that contains this target distance. - Interpolate the coordinates: For that segment, calculate the ratio of the remaining distance to the segment’s total length, then use that to interpolate between the segment’s start and end coordinates. This gives you the exact latitude/longitude of your meeting spot.
Example Code Snippet (JavaScript)
// Assume we have the full leg object from Directions API const totalTrafficSeconds = leg.duration_in_traffic.value; const targetSeconds = totalTrafficSeconds / 2; let accumulatedSeconds = 0; let targetStep = null; let stepRatio = 0; // Find which step contains the midpoint time for (const step of leg.steps) { const stepTrafficSeconds = step.duration_in_traffic.value; if (accumulatedSeconds + stepTrafficSeconds <= targetSeconds) { accumulatedSeconds += stepTrafficSeconds; } else { targetStep = step; stepRatio = (targetSeconds - accumulatedSeconds) / stepTrafficSeconds; break; } } // Decode the step's polyline const path = google.maps.geometry.encoding.decodePath(targetStep.polyline.points); // Calculate total path length and segment lengths let totalPathLength = 0; const segmentLengths = []; for (let i = 0; i < path.length - 1; i++) { const segmentLength = google.maps.geometry.spherical.computeDistanceBetween(path[i], path[i+1]); segmentLengths.push(segmentLength); totalPathLength += segmentLength; } // Find the exact meeting point const targetDistance = totalPathLength * stepRatio; let currentDistance = 0; let meetingPoint = null; for (let i = 0; i < segmentLengths.length; i++) { if (currentDistance + segmentLengths[i] >= targetDistance) { const segmentRatio = (targetDistance - currentDistance) / segmentLengths[i]; // Interpolate latitude and longitude const lat = path[i].lat() + (path[i+1].lat() - path[i].lat()) * segmentRatio; const lng = path[i].lng() + (path[i+1].lng() - path[i].lng()) * segmentRatio; meetingPoint = new google.maps.LatLng(lat, lng); break; } currentDistance += segmentLengths[i]; } // meetingPoint now holds the exact coordinates for your midpoint meeting spot
Key Notes
- Make sure both users use the same real-time traffic data (i.e., fetch the route at the same time) to ensure the midpoint aligns.
- If your route has multiple legs (e.g., transfers), repeat this process across legs until you reach the target duration.
内容的提问来源于stack exchange,提问作者RAHUL SRV




