1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229
| <!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>[Google Maps] Itinéraire avec étapes</title>
<meta name="Author" content="NoSmoking">
<meta name="DVP-discussion" content="d2106048">
<meta name="description" content="[Google Maps] Ajout/suppression dynamique d'étapes pour le calcul d'un itinéraire.">
<style>
html, body {margin: 0;padding: 0;font: 1em/1.5 Verdana,sans-serif;}
h1, h2, h3 {margin: .25em 0;color: #069;}
time {float: right;margin: .5em;font-size: 0.9em;color: #888;}
main {display: block;margin: auto;max-width: 60em;}
section {position: relative;margin: 0 1em 1em;}
#map {
height: 30em;
margin-bottom: 1em;
border: 1px solid #CCC;
}
button, input {
font: inherit;
}
.form {
padding: .5em;
border: 1px solid #CCC;
font-size: .9em;
}
.form label {
display: inline-block;
min-width: 6em;
}
.form input {
width: 25em;
}
#liste-etapes {
counter-reset: nbrEtape;
margin: 0 .5em;
padding: 0 .5em;
border-left: 2px solid #CCC;
}
.etape {
display: flex;
padding: .25em;
}
.etape label {
counter-increment: nbrEtape;
display: inline-block;
min-width: 6em;
}
.etape label::after {
content: "Etape "counter( nbrEtape) " :";
}
.etape button {
margin-left: .25em;
}
.etape button.remove_field {
font-weight: bold;
color: #A00;
}
#directions-panel {
font-size: .9em;
}
</style>
</head>
<body>
<main>
<header>
<time datetime="2021-03-23">Mars 2021</time>
<h1>Itinéraire avec étapes</h1>
</header>
<div id="map"></div>
<div class="form">
<p>
<label>Départ :</label>
<input id="start" type="text" value="">
<button class="add_field_button">Ajouter une étape</button>
</p>
<div class="input_fields_wrap">
<ul id="liste-etapes">
</ul>
</div>
<p><a name="resultat"></a></p>
<p>
<label>Arrivé :</label>
<input id="end" type="text" value="">
</p>
<p>
<button id="submit">Calculer l'itinéraire</button>
<button id="reset">Reset</button>
</p>
</div>
<div id="directions-panel"></div>
</main>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js" integrity="sha384-ZvpUoO/+PpLXR1lu4jmpXWu80pZlYUAfxl5NsBMWOEPSjUn/6Z/hRTt8+pR6L4N2" crossorigin="anonymous"></script>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=CLE_API&callback=initMap&libraries=places"></script>
<script>
function initMap() {
google.maps.event.addDomListener(window, 'load', function() {
var origin = new google.maps.places.Autocomplete(document.getElementById('start'));
var destination = new google.maps.places.Autocomplete(document.getElementById('end'));
});
var directionsService = new google.maps.DirectionsService;
var map = new google.maps.Map(document.getElementById('map'), {
"zoom": 5,
"backgroundColor": "#FFF",
"center": {
lat: 46.80,
lng: 2.65
}
});
const oDirectionsDisplay = new google.maps.DirectionsRenderer;
oDirectionsDisplay.setMap(map);
oDirectionsDisplay.setPanel(document.getElementById('directions-panel'));
// Affiche l'itinéraire
document.getElementById('submit').addEventListener('click', function() {
calculateAndDisplayRoute(directionsService, oDirectionsDisplay);
});
// Efface l'itinéraire affiché
document.getElementById("reset").addEventListener('click', function() {
// suppression des étapes
const btnEtape = document.querySelectorAll(".remove_field");
btnEtape.forEach((btn)=> btn.click());
// mise des input à zéro
const inputs = document.querySelectorAll(".form input");
inputs.forEach((input)=> input.value = "");
// vidage brut de l'itinéraire
oDirectionsDisplay.setDirections({routes:[]});
});
}
function calculateAndDisplayRoute(directionsService, directionsDisplay) {
var waypts = [];
var points = document.getElementsByName("waypoints[]");
for (var i = 0; i < points.length; i++) {
// il faut au minimum tester que la valeur est non vide
const data = points[i].value.trim();
if (data) {
waypts.push({
location: data,
stopover: true
});
}
}
directionsService.route({
origin: document.getElementById('start').value,
destination: document.getElementById('end').value,
waypoints: waypts,
optimizeWaypoints: true,
travelMode: 'DRIVING'
},
function(response, status) {
if (status === 'OK') {
directionsDisplay.setDirections(response);
}
else {
window.alert('Impossible de tracer l\'itinéraire. Cause : ' + status + '\n\nAvez vous mis au moins une étape ?\n\nAvez vous renseigné l\'état pour chaque étape (ex : Page, arizona ou Moab, utah) ?');
}
});
}
/**
* https://stackoverflow.com/questions/21024090/google-places-autocomplete-how-to-clean-up-pac-container
* by Driver : https://stackoverflow.com/users/7143894/driver
*/
function getAutocompletePacContainer(autocomplete) {
const place = autocomplete.gm_accessors_.place;
const placeKey = Object.keys(place).find((value) => (
(typeof(place[value]) === 'object') && (place[value].hasOwnProperty('gm_accessors_'))
));
const input = place[placeKey].gm_accessors_.input[placeKey];
const inputKey = Object.keys(input).find((value) => (
(input[value].classList && input[value].classList.contains('pac-container'))
));
return input[inputKey];
}
$(document).ready(function() {
// Ajouter des étapes
const MAX_ETAPE = 23;
const $wrapper = $("#liste-etapes");
const $addButton = $(".add_field_button");
$addButton.on("click", function(e) {
e.preventDefault();
const nbr = $("[name='waypoints[]']").length;
if (nbr < MAX_ETAPE) {
// création des éléments, une façon de faire
$etape = $("<li>")
.addClass("etape");
$label = $("<label>");
$input = $("<input>")
.addClass("waypoints")
.attr({
"name": "waypoints[]",
"placeholder": "Sous la forme : ville, état"
});
$btn = $("<button>")
.addClass("remove_field")
.text("✖");
// ajout des éléments étapes
$etape.append($label, $input, $btn);
$wrapper.append($etape);
// init autoComplete
const auto = new google.maps.places.Autocomplete($input[0]);
// on garde la réf. pour la suppression
$btn.data("autocomplete", auto);
}
else {
alert("Pas plus de " + (MAX_ETAPE + 2) + " étapes en comptant le départ et l'arrivé SVP...");
}
});
$wrapper.on("click", ".remove_field", function(e) {
e.preventDefault();
const auto = $(this).data("autocomplete");
getAutocompletePacContainer(auto).remove();
$(this).parent().remove();
});
});
</script>
</body>
</html> |
Partager