我正在开发一个 JavaScript 项目,旨在创建一条路线,同时考虑电动汽车充电站的停靠点。路线准备好后,用户可以单击一个按钮,将该路线重定向到 Google 地图。我就是这样做的。
document.getElementById('openMapBtn').addEventListener('click', function() {
var googleMapsLink = "https://www.google.com/maps/dir/";
// Ajouter l'origine
googleMapsLink += encodeURIComponent(document.getElementById("from").value);
// Ajouter les étapes intermédiaires
infosBornes.forEach(function(borne) {
googleMapsLink += "/" + encodeURIComponent(borne.adresse);
});
// Ajouter la destination
googleMapsLink += "/" + encodeURIComponent(document.getElementById("to").value);
// Vérifier si l'utilisateur veut éviter les autoroutes
var avoidHighwaysStatut = document.getElementById('avoidHighways');
if (avoidHighwaysStatut.checked) {
googleMapsLink += "/&dirflg=h,t";
}
// Ouvrir le lien dans une nouvelle fenêtre
window.open(googleMapsLink);
});
问题就在这里
if (avoidHighwaysStatut.checked) { googleMapsLink += "/&dirflg=h,t"; }
如何修复此错误并避免高速公路:/谢谢!
首先,正如google地图方向URL文档中提到的,查询参数
?api=1
是必需的。如果缺少,所有参数都将被删除。你缺少那个。此外,还需要使用查询参数指定出发地和目的地。例如:
https://www.google.com/maps/dir/?api=1&origin=/NC+State+University+NC&destination=伯灵顿+NC
但是,官方文档中似乎没有指定避开高速公路的参数,因此您可能需要使用带有编码
data
的重定向URL,这些参数是由!
分隔的一堆参数。
第一个数字是容器 ID,第二个字符似乎是容器类型(我认为
m
表示嵌套容器,b
表示布尔),后面跟着一个数字,表示该容器下分组了多少个参数。 1b1
似乎是无高速公路选项,并且它在 4m -> 4m->2m 以下,结果 !4m3!4m2!2m1!1b1
。
https://www.google.com/maps/dir/NC+State+University+NC/伯灵顿+NC/data=!4m3!4m2!2m1!1b1
抱歉,我找到了解决方案,就在这里。
if (avoidHighwaysStatut.checked) { googleMapsLink += "/data=!4m3!4m2!2m1!2b1"; }