]> git.openstreetmap.org Git - rails.git/blob - app/assets/javascripts/index/directions.js
8d9263323e44c154f60a77ede80f1eb8425da3df
[rails.git] / app / assets / javascripts / index / directions.js
1 //= require_self
2 //= require_tree ./directions
3 //= require qs/dist/qs
4
5 OSM.Directions = function (map) {
6   var awaitingRoute; // true if we've asked the engine for a route and are waiting to hear back
7   var chosenEngine;
8
9   var popup = L.popup({ autoPanPadding: [100, 100] });
10
11   var polyline = L.polyline([], {
12     color: "#03f",
13     opacity: 0.3,
14     weight: 10
15   });
16
17   var highlight = L.polyline([], {
18     color: "#ff0",
19     opacity: 0.5,
20     weight: 12
21   });
22
23   var endpointDragCallback = function (dragging) {
24     if (map.hasLayer(polyline)) {
25       getRoute(false, !dragging);
26     }
27   };
28
29   var endpoints = [
30     Endpoint($("input[name='route_from']"), OSM.MARKER_GREEN, endpointDragCallback),
31     Endpoint($("input[name='route_to']"), OSM.MARKER_RED, endpointDragCallback)
32   ];
33
34   var expiry = new Date();
35   expiry.setYear(expiry.getFullYear() + 10);
36
37   var engines = OSM.Directions.engines;
38
39   engines.sort(function (a, b) {
40     var localised_a = I18n.t("javascripts.directions.engines." + a.id),
41         localised_b = I18n.t("javascripts.directions.engines." + b.id);
42     return localised_a.localeCompare(localised_b);
43   });
44
45   var select = $("select.routing_engines");
46
47   engines.forEach(function (engine, i) {
48     select.append("<option value='" + i + "'>" + I18n.t("javascripts.directions.engines." + engine.id) + "</option>");
49   });
50
51   function Endpoint(input, iconUrl, dragCallback) {
52     var endpoint = {};
53
54     endpoint.marker = L.marker([0, 0], {
55       icon: L.icon({
56         iconUrl: iconUrl,
57         iconSize: [25, 41],
58         iconAnchor: [12, 41],
59         popupAnchor: [1, -34],
60         shadowUrl: OSM.MARKER_SHADOW,
61         shadowSize: [41, 41]
62       }),
63       draggable: true,
64       autoPan: true
65     });
66
67     endpoint.marker.on("drag dragend", function (e) {
68       var dragging = (e.type === "drag");
69       if (dragging && !chosenEngine.draggable) return;
70       if (dragging && awaitingRoute) return;
71       endpoint.setLatLng(e.target.getLatLng());
72       dragCallback(dragging);
73     });
74
75     input.on("keydown", function () {
76       input.removeClass("is-invalid");
77     });
78
79     input.on("change", function (e) {
80       // make text the same in both text boxes
81       var value = e.target.value;
82       endpoint.setValue(value);
83     });
84
85     endpoint.setValue = function (value, latlng) {
86       endpoint.value = value;
87       delete endpoint.latlng;
88       input.removeClass("is-invalid");
89       input.val(value);
90
91       if (latlng) {
92         endpoint.setLatLng(latlng);
93       } else {
94         endpoint.getGeocode();
95       }
96     };
97
98     endpoint.getGeocode = function () {
99       // if no one has entered a value yet, then we can't geocode, so don't
100       // even try.
101       if (!endpoint.value) {
102         return;
103       }
104
105       endpoint.awaitingGeocode = true;
106
107       var viewbox = map.getBounds().toBBoxString(); // <sw lon>,<sw lat>,<ne lon>,<ne lat>
108
109       $.getJSON(OSM.NOMINATIM_URL + "search?q=" + encodeURIComponent(endpoint.value) + "&format=json&viewbox=" + viewbox, function (json) {
110         endpoint.awaitingGeocode = false;
111         endpoint.hasGeocode = true;
112         if (json.length === 0) {
113           input.addClass("is-invalid");
114           alert(I18n.t("javascripts.directions.errors.no_place", { place: endpoint.value }));
115           return;
116         }
117
118         endpoint.setLatLng(L.latLng(json[0]));
119
120         input.val(json[0].display_name);
121
122         getRoute(true, true);
123       });
124     };
125
126     endpoint.setLatLng = function (ll) {
127       var precision = OSM.zoomPrecision(map.getZoom());
128       input.val(ll.lat.toFixed(precision) + ", " + ll.lng.toFixed(precision));
129       endpoint.hasGeocode = true;
130       endpoint.latlng = ll;
131       endpoint.marker
132         .setLatLng(ll)
133         .addTo(map);
134     };
135
136     return endpoint;
137   }
138
139   $(".directions_form .reverse_directions").on("click", function () {
140     var coordFrom = endpoints[0].latlng,
141         coordTo = endpoints[1].latlng,
142         routeFrom = "",
143         routeTo = "";
144     if (coordFrom) {
145       routeFrom = coordFrom.lat + "," + coordFrom.lng;
146     }
147     if (coordTo) {
148       routeTo = coordTo.lat + "," + coordTo.lng;
149     }
150
151     OSM.router.route("/directions?" + Qs.stringify({
152       from: $("#route_to").val(),
153       to: $("#route_from").val(),
154       route: routeTo + ";" + routeFrom
155     }));
156   });
157
158   $(".directions_form .btn-close").on("click", function (e) {
159     e.preventDefault();
160     var route_from = endpoints[0].value;
161     if (route_from) {
162       OSM.router.route("/?query=" + encodeURIComponent(route_from) + OSM.formatHash(map));
163     } else {
164       OSM.router.route("/" + OSM.formatHash(map));
165     }
166   });
167
168   function formatDistance(m) {
169     if (m < 1000) {
170       return I18n.t("javascripts.directions.distance_m", { distance: Math.round(m) });
171     } else if (m < 10000) {
172       return I18n.t("javascripts.directions.distance_km", { distance: (m / 1000.0).toFixed(1) });
173     } else {
174       return I18n.t("javascripts.directions.distance_km", { distance: Math.round(m / 1000) });
175     }
176   }
177
178   function formatHeight(m) {
179     return I18n.t("javascripts.directions.distance_m", { distance: Math.round(m) });
180   }
181
182   function formatTime(s) {
183     var m = Math.round(s / 60);
184     var h = Math.floor(m / 60);
185     m -= h * 60;
186     return h + ":" + (m < 10 ? "0" : "") + m;
187   }
188
189   function findEngine(id) {
190     return engines.findIndex(function (engine) {
191       return engine.id === id;
192     });
193   }
194
195   function setEngine(index) {
196     chosenEngine = engines[index];
197     select.val(index);
198   }
199
200   function getRoute(fitRoute, reportErrors) {
201     // Cancel any route that is already in progress
202     if (awaitingRoute) awaitingRoute.abort();
203
204     // go fetch geocodes for any endpoints which have not already
205     // been geocoded.
206     for (var ep_i = 0; ep_i < 2; ++ep_i) {
207       var endpoint = endpoints[ep_i];
208       if (!endpoint.hasGeocode && !endpoint.awaitingGeocode) {
209         endpoint.getGeocode();
210       }
211     }
212     if (endpoints[0].awaitingGeocode || endpoints[1].awaitingGeocode) {
213       return;
214     }
215
216     var o = endpoints[0].latlng,
217         d = endpoints[1].latlng;
218
219     if (!o || !d) return;
220     $("header").addClass("closed");
221
222     var precision = OSM.zoomPrecision(map.getZoom());
223
224     OSM.router.replace("/directions?" + Qs.stringify({
225       engine: chosenEngine.id,
226       route: o.lat.toFixed(precision) + "," + o.lng.toFixed(precision) + ";" +
227              d.lat.toFixed(precision) + "," + d.lng.toFixed(precision)
228     }));
229
230     // copy loading item to sidebar and display it. we copy it, rather than
231     // just using it in-place and replacing it in case it has to be used
232     // again.
233     $("#sidebar_content").html($(".directions_form .loader_copy").html());
234     map.setSidebarOverlaid(false);
235
236     awaitingRoute = chosenEngine.getRoute([o, d], function (err, route) {
237       awaitingRoute = null;
238
239       if (err) {
240         map.removeLayer(polyline);
241
242         if (reportErrors) {
243           $("#sidebar_content").html("<div class=\"alert alert-danger\">" + I18n.t("javascripts.directions.errors.no_route") + "</div>");
244         }
245
246         return;
247       }
248
249       polyline
250         .setLatLngs(route.line)
251         .addTo(map);
252
253       if (fitRoute) {
254         map.fitBounds(polyline.getBounds().pad(0.05));
255       }
256
257       var distanceText = $("<p>").append(
258         I18n.t("javascripts.directions.distance") + ": " + formatDistance(route.distance) + ". " +
259         I18n.t("javascripts.directions.time") + ": " + formatTime(route.time) + ".");
260       if (typeof route.ascend !== "undefined" && typeof route.descend !== "undefined") {
261         distanceText.append(
262           $("<br>"),
263           I18n.t("javascripts.directions.ascend") + ": " + formatHeight(route.ascend) + ". " +
264           I18n.t("javascripts.directions.descend") + ": " + formatHeight(route.descend) + ".");
265       }
266
267       var turnByTurnTable = $("<table class='table table-hover table-sm mb-3'>")
268         .append($("<tbody>"));
269       var directionsCloseButton = $("<button type='button' class='btn-close'>")
270         .attr("aria-label", I18n.t("javascripts.close"));
271
272       $("#sidebar_content")
273         .empty()
274         .append(
275           $("<div class='d-flex'>").append(
276             $("<h2 class='flex-grow-1 text-break'>")
277               .text(I18n.t("javascripts.directions.directions")),
278             $("<div>").append(directionsCloseButton)),
279           distanceText,
280           turnByTurnTable
281         );
282
283       // Add each row
284       route.steps.forEach(function (step) {
285         var ll = step[0],
286             direction = step[1],
287             instruction = step[2],
288             dist = step[3],
289             lineseg = step[4];
290
291         if (dist < 5) {
292           dist = "";
293         } else if (dist < 200) {
294           dist = String(Math.round(dist / 10) * 10) + "m";
295         } else if (dist < 1500) {
296           dist = String(Math.round(dist / 100) * 100) + "m";
297         } else if (dist < 5000) {
298           dist = String(Math.round(dist / 100) / 10) + "km";
299         } else {
300           dist = String(Math.round(dist / 1000)) + "km";
301         }
302
303         var row = $("<tr class='turn'/>");
304         row.append("<td class='border-0'><div class='direction i" + direction + "'/></td> ");
305         row.append("<td>" + instruction);
306         row.append("<td class='distance text-body-secondary text-end'>" + dist);
307
308         row.on("click", function () {
309           popup
310             .setLatLng(ll)
311             .setContent("<p>" + instruction + "</p>")
312             .openOn(map);
313         });
314
315         row.hover(function () {
316           highlight
317             .setLatLngs(lineseg)
318             .addTo(map);
319         }, function () {
320           map.removeLayer(highlight);
321         });
322
323         turnByTurnTable.append(row);
324       });
325
326       $("#sidebar_content").append("<p class=\"text-center\">" +
327         I18n.t("javascripts.directions.instructions.courtesy", { link: chosenEngine.creditline }) +
328         "</p>");
329
330       directionsCloseButton.on("click", function () {
331         map.removeLayer(polyline);
332         $("#sidebar_content").html("");
333         map.setSidebarOverlaid(true);
334         // TODO: collapse width of sidebar back to previous
335       });
336     });
337   }
338
339   var chosenEngineIndex = findEngine("fossgis_osrm_car");
340   if (Cookies.get("_osm_directions_engine")) {
341     chosenEngineIndex = findEngine(Cookies.get("_osm_directions_engine"));
342   }
343   setEngine(chosenEngineIndex);
344
345   select.on("change", function (e) {
346     chosenEngine = engines[e.target.selectedIndex];
347     Cookies.set("_osm_directions_engine", chosenEngine.id, { secure: true, expires: expiry, path: "/", samesite: "lax" });
348     getRoute(true, true);
349   });
350
351   $(".directions_form").on("submit", function (e) {
352     e.preventDefault();
353     getRoute(true, true);
354   });
355
356   $(".routing_marker_column img").on("dragstart", function (e) {
357     var dt = e.originalEvent.dataTransfer;
358     dt.effectAllowed = "move";
359     var dragData = { type: $(this).data("type") };
360     dt.setData("text", JSON.stringify(dragData));
361     if (dt.setDragImage) {
362       var img = $("<img>").attr("src", $(e.originalEvent.target).attr("src"));
363       dt.setDragImage(img.get(0), 12, 21);
364     }
365   });
366
367   var page = {};
368
369   page.pushstate = page.popstate = function () {
370     $(".search_form").hide();
371     $(".directions_form").show();
372
373     $("#map").on("dragend dragover", function (e) {
374       e.preventDefault();
375     });
376
377     $("#map").on("drop", function (e) {
378       e.preventDefault();
379       var oe = e.originalEvent;
380       var dragData = JSON.parse(oe.dataTransfer.getData("text"));
381       var type = dragData.type;
382       var pt = L.DomEvent.getMousePosition(oe, map.getContainer()); // co-ordinates of the mouse pointer at present
383       pt.y += 20;
384       var ll = map.containerPointToLatLng(pt);
385       endpoints[type === "from" ? 0 : 1].setLatLng(ll);
386       getRoute(true, true);
387     });
388
389     var params = Qs.parse(location.search.substring(1)),
390         route = (params.route || "").split(";"),
391         from = route[0] && L.latLng(route[0].split(",")),
392         to = route[1] && L.latLng(route[1].split(","));
393
394     if (params.engine) {
395       var engineIndex = findEngine(params.engine);
396
397       if (engineIndex >= 0) {
398         setEngine(engineIndex);
399       }
400     }
401
402     endpoints[0].setValue(params.from || "", from);
403     endpoints[1].setValue(params.to || "", to);
404
405     map.setSidebarOverlaid(!from || !to);
406
407     getRoute(true, true);
408   };
409
410   page.load = function () {
411     page.pushstate();
412   };
413
414   page.unload = function () {
415     $(".search_form").show();
416     $(".directions_form").hide();
417     $("#map").off("dragend dragover drop");
418
419     map
420       .removeLayer(popup)
421       .removeLayer(polyline)
422       .removeLayer(endpoints[0].marker)
423       .removeLayer(endpoints[1].marker);
424   };
425
426   return page;
427 };
428
429 OSM.Directions.engines = [];
430
431 OSM.Directions.addEngine = function (engine, supportsHTTPS) {
432   if (document.location.protocol === "http:" || supportsHTTPS) {
433     OSM.Directions.engines.push(engine);
434   }
435 };