调用Google Maps Distance Service API成功后,如何获取路线短链接(shortURL)
获取Google Maps路线短链接(Short URL)的解决方案
嘿,我刚好碰到过类似的需求!DirectionsService本身确实不会直接返回路线的短链接,不过咱们可以通过构造原生Google Maps路线长链接 + 生成短链接的方式来实现,客户端点击短链接就能直接跳转到对应路线啦。
一、先构造原生Google Maps路线长链接
Google Maps提供了通用的路线链接格式,我们可以根据获取到的路线参数直接拼接:
基础格式(跳转到起点到终点的路线选择页)
// 替换origin、destination、travelMode为你的实际参数 const originStr = encodeURIComponent(origin); // origin可以是地址字符串或经纬度(如"37.7749,-122.4194") const destStr = encodeURIComponent(destination); const travelMode = 'driving'; // 对应你的travelMode:driving/walking/bicycling/transit const longUrl = `https://www.google.com/maps/dir/?api=1&origin=${originStr}&destination=${destStr}&travelmode=${travelMode}`;
进阶格式(直接跳转到某条特定的备选路线)
因为你开启了provideRouteAlternatives: true,会返回多条路线。如果要让短链接直接跳转到某条特定路线,需要带上该路线的overview_polyline:
// 在directionsService的回调中处理每条路线 response.routes.forEach((route, index) => { // 获取当前路线的编码折线 const polyline = route.overview_polyline.encodePath(); // 拼接带特定路线的长链接 const specificLongUrl = `https://www.google.com/maps/dir/?api=1&origin=${originStr}&destination=${destStr}&travelmode=${travelMode}&waypoints=enc:${polyline}`; });
二、把长链接转成短链接
长链接可能太长,需要缩短。这里要注意:前端直接调用短链接API容易碰到跨域问题,建议通过后端处理。以下是两种常见方案:
方案1:使用Firebase Dynamic Links(Google官方推荐)
Google的URL Shortener API已弃用,现在推荐用Firebase Dynamic Links。你可以在后端集成Firebase SDK,传入长链接生成短链接:
// 后端Node.js示例(需要先安装firebase-admin) const admin = require('firebase-admin'); admin.initializeApp(); async function generateShortUrl(longUrl) { const link = await admin.dynamicLinks().createShortLink({ dynamicLinkInfo: { link: longUrl, domainUriPrefix: 'https://yourdomain.page.link' // 替换为你的Firebase动态链接域名 } }); return link.shortLink; }
方案2:使用第三方短链接服务
如果不想用Firebase,也可以选择Bitly、TinyURL等第三方服务,它们都提供API可以生成短链接,只需要在后端调用对应接口即可。
三、结合你的代码完整示例
把上面的逻辑整合到你的现有代码中:
var directionsService = new google.maps.DirectionsService; directionsService.route({ origin: origin, destination: destination, travelMode: 'DRIVING', provideRouteAlternatives: true, unitSystem: google.maps.UnitSystem.METRIC }, function(response, status) { if (status === 'OK') { const originStr = encodeURIComponent(origin); const destStr = encodeURIComponent(destination); const travelMode = 'driving'; response.routes.forEach(function(route, index) { // 构造特定路线的长链接 const polyline = route.overview_polyline.encodePath(); const longUrl = `https://www.google.com/maps/dir/?api=1&origin=${originStr}&destination=${destStr}&travelmode=${travelMode}&waypoints=enc:${polyline}`; // 调用后端接口生成短链接 fetch('/api/generate-short-url', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ url: longUrl }) }) .then(res => res.json()) .then(data => { console.log(`第${index+1}条路线的短链接:${data.shortUrl}`); // 这里可以把短链接传递给客户端使用 }) .catch(err => console.error('生成短链接失败:', err)); }); } else { console.error('获取路线失败:', status); } });
几个注意点
- 一定要用
encodeURIComponent对origin和destination进行编码,避免地址中的特殊字符破坏链接格式 - 如果不需要指定特定路线,去掉
waypoints=enc:${polyline}即可,链接会跳转到Google Maps的路线选择页面 - 短链接生成必须通过后端处理,前端直接调用第三方API会有跨域限制,且容易暴露API密钥
内容的提问来源于stack exchange,提问作者usmany
相关产品推荐
相关产品推荐

