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