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