You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

在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.

1. Calculate the Midpoint Based on Traffic Duration

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 numeric value field, which is in seconds, for precise calculations).
  • Iterate through route steps: Start accumulating the duration_in_traffic.value of 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.
2. Get Precise Polyline Coordinates & Pinpoint the Meeting Spot

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 polyline package (install with pip install polyline) and call polyline.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:

  1. Calculate the total length of the step’s path: Use a spherical distance calculator (like google.maps.geometry.spherical.computeDistanceBetween() in JS, or geopy in Python) to sum the distance between each consecutive pair of coordinates in the path.
  2. Find the segment matching your ratio: Multiply the total path length by step_ratio to 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.
  3. 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

火山引擎 最新活动