I am working on a JavaScript project aimed at creating a route while considering stops at electric vehicle charging stations. Once the route is ready, the user can click on a button that redirects this route to Google Maps. Here’s how I do it.
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);
});
The problem is here
if (avoidHighwaysStatut.checked) {
googleMapsLink += "/&dirflg=h,t";
}
How to fix this error and avoid highWay :/ Thank’s !
2
Answers
My apologies, I found the solution, here it is.
if (avoidHighwaysStatut.checked) { googleMapsLink += "/data=!4m3!4m2!2m1!2b1"; }
First, as mentioned in the google map direction URL documentation, the query parameter
?api=1
is required. If it is missing, all parameters will be removed. You are missing that. Also, the origin and destination needs to be specified using query parameters as well. For example:https://www.google.com/maps/dir/?api=1&origin=/NC+State+University+NC&destination=Burlington+NC
However, in the official doc there is no parameter that specifies avoiding highway, hence one hacky option is to use the undocumented
maps/dir/{origin}/{destination}/data
url, following with a bunch of parameters separated by!
. In your case, you’ll needdata=!4m3!4m2!2m1!1b1
.There is a SO post about the observations that people have made about these parameters. In your example, in each of the parameters, the first number is the parameter ID, and the second character is the parameter type.
m
means it’s a container that nests parameters, andb
means bool. The third number’s meaning depends on the container type. Form
it indicates how many parameters are grouped under this container.1b1
is the no highway option, and it is under containers4m->4m->2m
, resulting!4m3!4m2!2m1!1b1
.https://www.google.com/maps/dir/NC+State+University+NC/Burlington+NC/data=!4m3!4m2!2m1!1b1
However, as mentioned in the comment, one must keep in mind that this is undocumented which means it’s subject to be changed anytime without notice. If creating a Map ID is feasible (might be free or billed depends on your use case), the better options is to use the Maps JavaScript API, which includes the avoidHighways option.