You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何沿路线每100米获取点位坐标?已查Google Maps API未得方法

技术解决方案

步骤1:通过Google Maps Directions API获取路线Polyline

调用Directions API,传入起点、终点坐标及出行模式(如驾车/步行),从返回结果中提取routes.legs.steps.polyline.points(需拼接所有step的polyline以获得完整精确路径,若对精度要求不高,也可使用overview_polyline.points的简化路径)。

示例请求参数(伪代码):

origin: "起始点纬度,起始点经度"
destination: "终点纬度,终点经度"
mode: "driving"
key: "你的API密钥"

步骤2:解码Polyline为经纬度坐标数组

利用Google官方提供的Polyline解码工具(或自行实现解码逻辑),将编码后的points字符串转换为包含多个{lat: 纬度值, lng: 经度值}对象的数组。

JavaScript示例(使用官方库):

import { decode } from "@googlemaps/polyline";

const encodedPolyline = "API返回的polyline字符串";
const pathCoordinates = decode(encodedPolyline); // 得到完整路径的坐标数组

步骤3:沿路径插值生成每隔100米的点位

基于解码后的坐标数组,通过计算相邻点距离、分段插值的方式生成间隔100米的途经点:

  • 遍历每一对相邻坐标点,用Haversine公式计算两点间的球面距离(单位:米)
  • 若两点距离大于100米,计算需插入的点数,按比例在两点间插值生成中间点
  • 收集所有原始点与插值点,确保相邻点间距不超过100米

Haversine公式计算距离(JavaScript示例)

function getDistance(lat1, lng1, lat2, lng2) {
  const earthRadius = 6371000; // 地球半径,单位米
  const dLat = (lat2 - lat1) * Math.PI / 180;
  const dLng = (lng2 - lng1) * Math.PI / 180;
  const a = 
    Math.sin(dLat/2) * Math.sin(dLat/2) +
    Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) * 
    Math.sin(dLng/2) * Math.sin(dLng/2); 
  const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 
  return earthRadius * c;
}

插值生成中间点(JavaScript示例)

function insertMiddlePoints(start, end, step = 100) {
  const middlePoints = [];
  const totalDistance = getDistance(start.lat, start.lng, end.lat, end.lng);

  if (totalDistance <= step) {
    middlePoints.push(end);
    return middlePoints;
  }

  const stepCount = Math.floor(totalDistance / step);
  const latDelta = end.lat - start.lat;
  const lngDelta = end.lng - start.lng;

  for (let i = 1; i <= stepCount; i++) {
    const ratio = (i * step) / totalDistance;
    const lat = start.lat + latDelta * ratio;
    const lng = start.lng + lngDelta * ratio;
    middlePoints.push({ lat, lng });
  }

  // 补充最后一段不足100米的终点
  const lastInserted = middlePoints[middlePoints.length - 1];
  if (getDistance(lastInserted.lat, lastInserted.lng, end.lat, end.lng) > step) {
    middlePoints.push(end);
  }

  return middlePoints;
}

// 处理整个路径生成最终点位数组
function generateAllPoints(path, step = 100) {
  const finalPoints = [path[0]]; // 包含起点
  for (let i = 0; i < path.length - 1; i++) {
    const interpolated = insertMiddlePoints(path[i], path[i+1], step);
    finalPoints.push(...interpolated);
  }
  return finalPoints;
}

注意事项

  • 优先使用routes.legs.steps.polyline拼接路径,比overview_polyline的简化路径精度更高
  • 注意控制API调用频率,避免超出Google Maps API的配额限制
  • 短距离内的线性插值误差可忽略,若需更高精度,可采用大地坐标系下的插值方法

内容的提问来源于stack exchange,提问作者burcu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 23:40:38