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

如何在NodeJS后端服务中使用Google Maps Directions Service

解决Node.js中@google/maps模块调用Directions服务的错误

你遇到的mapsClient.directions.route is not a function错误,核心原因是后端@google/maps模块的调用逻辑和前端Google Maps JS SDK完全不同,具体修正点如下:

1. 修正方法调用方式

后端模块中,Directions服务是直接通过mapsClient.directions()方法调用,不存在directions.route这个子方法——这是前端SDK独有的调用结构。

2. 适配REST API参数命名规则

后端模块对接的是Google Maps REST API,参数命名采用下划线格式,而非前端的驼峰格式,必须对应修改:

  • 前端travelMode → 后端mode(值需小写,如'driving')
  • 前端drivingOptions → 后端driving_options
  • 前端trafficModel → 后端traffic_model
  • 前端optimizeWaypoints → 后端optimize_waypoints

3. 修正后的完整代码

import googleMapsClient from '@google/maps';

const mapsClient = googleMapsClient.createClient({
  key: process.env.GOOGLE_MAPS_API_KEY,
  Promise: Promise // 配置Promise支持,避免回调式调用
});

mapsClient.directions({
  origin: {lat: 40.154570, lng: -111.573910},
  destination: {lat: 40.259250, lng: -111.698360},
  optimize_waypoints: true,
  mode: 'driving',
  driving_options: {
    traffic_model: 'optimistic'
  }
})
.asPromise() // 转换为Promise链式调用(若客户端已配置Promise也可省略)
.then(response => {
  console.log(response.json.routes, 'route response');
})
.catch(err => {
  console.error(err.message, 'directions request failed');
});

额外说明

你测试的geocode功能能正常工作,是因为它的调用逻辑符合后端模块的规范:直接调用mapsClient.geocode()方法,而非子方法——这和Directions的正确调用逻辑一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 11:31:12