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