]> git.openstreetmap.org Git - rails.git/blob - app/assets/javascripts/index/directions.js
Replace querystring parser with qs yarn module
[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 .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 Math.round(m) + "m";
173     } else if (m < 10000) {
174       return (m / 1000.0).toFixed(1) + "km";
175     } else {
176       return Math.round(m / 1000) + "km";
177     }
178   }
179
180   function formatTime(s) {
181     var m = Math.round(s / 60);
182     var h = Math.floor(m / 60);
183     m -= h * 60;
184     return h + ":" + (m < 10 ? "0" : "") + m;
185   }
186
187   function findEngine(id) {
188     return engines.findIndex(function (engine) {
189       return engine.id === id;
190     });
191   }
192
193   function setEngine(index) {
194     chosenEngine = engines[index];
195     select.val(index);
196   }
197
198   function getRoute(fitRoute, reportErrors) {
199     // Cancel any route that is already in progress
200     if (awaitingRoute) awaitingRoute.abort();
201
202     // go fetch geocodes for any endpoints which have not already
203     // been geocoded.
204     for (var ep_i = 0; ep_i < 2; ++ep_i) {
205       var endpoint = endpoints[ep_i];
206       if (!endpoint.hasGeocode && !endpoint.awaitingGeocode) {
207         endpoint.getGeocode();
208         awaitingGeocode = true;
209       }
210     }
211     if (endpoints[0].awaitingGeocode || endpoints[1].awaitingGeocode) {
212       awaitingGeocode = true;
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("<p class=\"search_results_error\">" + I18n.t("javascripts.directions.errors.no_route") + "</p>");
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 html = "<h2><a class=\"geolink\" href=\"#\">" +
258         "<span class=\"icon close\"></span></a>" + I18n.t("javascripts.directions.directions") +
259         "</h2><p id=\"routing_summary\">" +
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         html += "<br />" +
264           I18n.t("javascripts.directions.ascend") + ": " + Math.round(route.ascend) + "m. " +
265           I18n.t("javascripts.directions.descend") + ": " + Math.round(route.descend) + "m.";
266       }
267       html += "</p><table id=\"turnbyturn\" />";
268
269       $("#sidebar_content")
270         .html(html);
271
272       // Add each row
273       route.steps.forEach(function (step) {
274         var ll = step[0],
275             direction = step[1],
276             instruction = step[2],
277             dist = step[3],
278             lineseg = step[4];
279
280         if (dist < 5) {
281           dist = "";
282         } else if (dist < 200) {
283           dist = String(Math.round(dist / 10) * 10) + "m";
284         } else if (dist < 1500) {
285           dist = String(Math.round(dist / 100) * 100) + "m";
286         } else if (dist < 5000) {
287           dist = String(Math.round(dist / 100) / 10) + "km";
288         } else {
289           dist = String(Math.round(dist / 1000)) + "km";
290         }
291
292         var row = $("<tr class='turn'/>");
293         row.append("<td><div class='direction i" + direction + "'/></td> ");
294         row.append("<td class='instruction'>" + instruction);
295         row.append("<td class='distance'>" + dist);
296
297         row.on("click", function () {
298           popup
299             .setLatLng(ll)
300             .setContent("<p>" + instruction + "</p>")
301             .openOn(map);
302         });
303
304         row.hover(function () {
305           highlight
306             .setLatLngs(lineseg)
307             .addTo(map);
308         }, function () {
309           map.removeLayer(highlight);
310         });
311
312         $("#turnbyturn").append(row);
313       });
314
315       $("#sidebar_content").append("<p id=\"routing_credit\">" +
316         I18n.t("javascripts.directions.instructions.courtesy", { link: chosenEngine.creditline }) +
317         "</p>");
318
319       $("#sidebar_content a.geolink").on("click", function (e) {
320         e.preventDefault();
321         map.removeLayer(polyline);
322         $("#sidebar_content").html("");
323         map.setSidebarOverlaid(true);
324         // TODO: collapse width of sidebar back to previous
325       });
326     });
327   }
328
329   var chosenEngineIndex = findEngine("fossgis_osrm_car");
330   if ($.cookie("_osm_directions_engine")) {
331     chosenEngineIndex = findEngine($.cookie("_osm_directions_engine"));
332   }
333   setEngine(chosenEngineIndex);
334
335   select.on("change", function (e) {
336     chosenEngine = engines[e.target.selectedIndex];
337     $.cookie("_osm_directions_engine", chosenEngine.id, { expires: expiry, path: "/" });
338     if (map.hasLayer(polyline)) {
339       getRoute(true, true);
340     }
341   });
342
343   $(".directions_form").on("submit", function (e) {
344     e.preventDefault();
345     getRoute(true, true);
346   });
347
348   $(".routing_marker").on("dragstart", function (e) {
349     var dt = e.originalEvent.dataTransfer;
350     dt.effectAllowed = "move";
351     var dragData = { type: $(this).data("type") };
352     dt.setData("text", JSON.stringify(dragData));
353     if (dt.setDragImage) {
354       var img = $("<img>").attr("src", $(e.originalEvent.target).attr("src"));
355       dt.setDragImage(img.get(0), 12, 21);
356     }
357   });
358
359   var page = {};
360
361   page.pushstate = page.popstate = function () {
362     $(".search_form").hide();
363     $(".directions_form").show();
364
365     $("#map").on("dragend dragover", function (e) {
366       e.preventDefault();
367     });
368
369     $("#map").on("drop", function (e) {
370       e.preventDefault();
371       var oe = e.originalEvent;
372       var dragData = JSON.parse(oe.dataTransfer.getData("text"));
373       var type = dragData.type;
374       var pt = L.DomEvent.getMousePosition(oe, map.getContainer()); // co-ordinates of the mouse pointer at present
375       pt.y += 20;
376       var ll = map.containerPointToLatLng(pt);
377       endpoints[type === "from" ? 0 : 1].setLatLng(ll);
378       getRoute(true, true);
379     });
380
381     var params = Qs.parse(location.search.substring(1)),
382         route = (params.route || "").split(";"),
383         from = route[0] && L.latLng(route[0].split(",")),
384         to = route[1] && L.latLng(route[1].split(","));
385
386     if (params.engine) {
387       var engineIndex = findEngine(params.engine);
388
389       if (engineIndex >= 0) {
390         setEngine(engineIndex);
391       }
392     }
393
394     endpoints[0].setValue(params.from || "", from);
395     endpoints[1].setValue(params.to || "", to);
396
397     map.setSidebarOverlaid(!from || !to);
398
399     getRoute(true, true);
400   };
401
402   page.load = function () {
403     page.pushstate();
404   };
405
406   page.unload = function () {
407     $(".search_form").show();
408     $(".directions_form").hide();
409     $("#map").off("dragend dragover drop");
410
411     map
412       .removeLayer(popup)
413       .removeLayer(polyline)
414       .removeLayer(endpoints[0].marker)
415       .removeLayer(endpoints[1].marker);
416   };
417
418   return page;
419 };
420
421 OSM.Directions.engines = [];
422
423 OSM.Directions.addEngine = function (engine, supportsHTTPS) {
424   if (document.location.protocol === "http:" || supportsHTTPS) {
425     OSM.Directions.engines.push(engine);
426   }
427 };