]> git.openstreetmap.org Git - rails.git/blob - app/assets/javascripts/index/directions.js
rename internal variable
[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       var viewbox = map.getBounds().toBBoxString(); // <sw lon>,<sw lat>,<ne lon>,<ne lat>
109
110       $.getJSON(OSM.NOMINATIM_URL + "search?q=" + encodeURIComponent(endpoint.value) + "&format=json&viewbox=" + viewbox, function (json) {
111         endpoint.awaitingGeocode = false;
112         endpoint.hasGeocode = true;
113         if (json.length === 0) {
114           input.addClass("error");
115           alert(I18n.t("javascripts.directions.errors.no_place", { place: endpoint.value }));
116           return;
117         }
118
119         endpoint.setLatLng(L.latLng(json[0]));
120
121         input.val(json[0].display_name);
122
123         if (awaitingGeocode) {
124           awaitingGeocode = false;
125           getRoute(true, true);
126         }
127       });
128     };
129
130     endpoint.setLatLng = function (ll) {
131       var precision = OSM.zoomPrecision(map.getZoom());
132       input.val(ll.lat.toFixed(precision) + ", " + ll.lng.toFixed(precision));
133       endpoint.hasGeocode = true;
134       endpoint.latlng = ll;
135       endpoint.marker
136         .setLatLng(ll)
137         .addTo(map);
138     };
139
140     return endpoint;
141   }
142
143   $(".directions_form .reverse_directions").on("click", function () {
144     var coordFrom = endpoints[0].latlng,
145         coordTo = endpoints[1].latlng,
146         routeFrom = "",
147         routeTo = "";
148     if (coordFrom) {
149       routeFrom = coordFrom.lat + "," + coordFrom.lng;
150     }
151     if (coordTo) {
152       routeTo = coordTo.lat + "," + coordTo.lng;
153     }
154
155     OSM.router.route("/directions?" + querystring.stringify({
156       from: $("#route_to").val(),
157       to: $("#route_from").val(),
158       route: routeTo + ";" + routeFrom
159     }));
160   });
161
162   $(".directions_form .close").on("click", function (e) {
163     e.preventDefault();
164     var route_from = endpoints[0].value;
165     if (route_from) {
166       OSM.router.route("/?query=" + encodeURIComponent(route_from) + OSM.formatHash(map));
167     } else {
168       OSM.router.route("/" + OSM.formatHash(map));
169     }
170   });
171
172   function formatDistance(m) {
173     if (m < 1000) {
174       return Math.round(m) + "m";
175     } else if (m < 10000) {
176       return (m / 1000.0).toFixed(1) + "km";
177     } else {
178       return Math.round(m / 1000) + "km";
179     }
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         awaitingGeocode = true;
211       }
212     }
213     if (endpoints[0].awaitingGeocode || endpoints[1].awaitingGeocode) {
214       awaitingGeocode = true;
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?" + querystring.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     awaitingRoute = chosenEngine.getRoute([o, d], function (err, route) {
239       awaitingRoute = null;
240
241       if (err) {
242         map.removeLayer(polyline);
243
244         if (reportErrors) {
245           $("#sidebar_content").html("<p class=\"search_results_error\">" + I18n.t("javascripts.directions.errors.no_route") + "</p>");
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 html = "<h2><a class=\"geolink\" href=\"#\">" +
260         "<span class=\"icon close\"></span></a>" + I18n.t("javascripts.directions.directions") +
261         "</h2><p id=\"routing_summary\">" +
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         html += "<br />" +
266           I18n.t("javascripts.directions.ascend") + ": " + Math.round(route.ascend) + "m. " +
267           I18n.t("javascripts.directions.descend") + ": " + Math.round(route.descend) + "m.";
268       }
269       html += "</p><table id=\"turnbyturn\" />";
270
271       $("#sidebar_content")
272         .html(html);
273
274       // Add each row
275       route.steps.forEach(function (step) {
276         var ll = step[0],
277             direction = step[1],
278             instruction = step[2],
279             dist = step[3],
280             lineseg = step[4];
281
282         if (dist < 5) {
283           dist = "";
284         } else if (dist < 200) {
285           dist = String(Math.round(dist / 10) * 10) + "m";
286         } else if (dist < 1500) {
287           dist = String(Math.round(dist / 100) * 100) + "m";
288         } else if (dist < 5000) {
289           dist = String(Math.round(dist / 100) / 10) + "km";
290         } else {
291           dist = String(Math.round(dist / 1000)) + "km";
292         }
293
294         var row = $("<tr class='turn'/>");
295         row.append("<td><div class='direction i" + direction + "'/></td> ");
296         row.append("<td class='instruction'>" + instruction);
297         row.append("<td class='distance'>" + dist);
298
299         row.on("click", function () {
300           popup
301             .setLatLng(ll)
302             .setContent("<p>" + instruction + "</p>")
303             .openOn(map);
304         });
305
306         row.hover(function () {
307           highlight
308             .setLatLngs(lineseg)
309             .addTo(map);
310         }, function () {
311           map.removeLayer(highlight);
312         });
313
314         $("#turnbyturn").append(row);
315       });
316
317       $("#sidebar_content").append("<p id=\"routing_credit\">" +
318         I18n.t("javascripts.directions.instructions.courtesy", { link: chosenEngine.creditline }) +
319         "</p>");
320
321       $("#sidebar_content a.geolink").on("click", function (e) {
322         e.preventDefault();
323         map.removeLayer(polyline);
324         $("#sidebar_content").html("");
325         map.setSidebarOverlaid(true);
326         // TODO: collapse width of sidebar back to previous
327       });
328     });
329   }
330
331   var chosenEngineIndex = findEngine("fossgis_osrm_car");
332   if ($.cookie("_osm_directions_engine")) {
333     chosenEngineIndex = findEngine($.cookie("_osm_directions_engine"));
334   }
335   setEngine(chosenEngineIndex);
336
337   select.on("change", function (e) {
338     chosenEngine = engines[e.target.selectedIndex];
339     $.cookie("_osm_directions_engine", chosenEngine.id, { expires: expiry, path: "/" });
340     if (map.hasLayer(polyline)) {
341       getRoute(true, true);
342     }
343   });
344
345   $(".directions_form").on("submit", function (e) {
346     e.preventDefault();
347     getRoute(true, true);
348   });
349
350   $(".routing_marker").on("dragstart", function (e) {
351     var dt = e.originalEvent.dataTransfer;
352     dt.effectAllowed = "move";
353     var dragData = { type: $(this).data("type") };
354     dt.setData("text", JSON.stringify(dragData));
355     if (dt.setDragImage) {
356       var img = $("<img>").attr("src", $(e.originalEvent.target).attr("src"));
357       dt.setDragImage(img.get(0), 12, 21);
358     }
359   });
360
361   var page = {};
362
363   page.pushstate = page.popstate = function () {
364     $(".search_form").hide();
365     $(".directions_form").show();
366
367     $("#map").on("dragend dragover", function (e) {
368       e.preventDefault();
369     });
370
371     $("#map").on("drop", function (e) {
372       e.preventDefault();
373       var oe = e.originalEvent;
374       var dragData = JSON.parse(oe.dataTransfer.getData("text"));
375       var type = dragData.type;
376       var pt = L.DomEvent.getMousePosition(oe, map.getContainer()); // co-ordinates of the mouse pointer at present
377       pt.y += 20;
378       var ll = map.containerPointToLatLng(pt);
379       endpoints[type === "from" ? 0 : 1].setLatLng(ll);
380       getRoute(true, true);
381     });
382
383     var params = querystring.parse(location.search.substring(1)),
384         route = (params.route || "").split(";"),
385         from = route[0] && L.latLng(route[0].split(",")),
386         to = route[1] && L.latLng(route[1].split(","));
387
388     if (params.engine) {
389       var engineIndex = findEngine(params.engine);
390
391       if (engineIndex >= 0) {
392         setEngine(engineIndex);
393       }
394     }
395
396     endpoints[0].setValue(params.from || "", from);
397     endpoints[1].setValue(params.to || "", to);
398
399     map.setSidebarOverlaid(!from || !to);
400
401     getRoute(true, true);
402   };
403
404   page.load = function () {
405     page.pushstate();
406   };
407
408   page.unload = function () {
409     $(".search_form").show();
410     $(".directions_form").hide();
411     $("#map").off("dragend dragover drop");
412
413     map
414       .removeLayer(popup)
415       .removeLayer(polyline)
416       .removeLayer(endpoints[0].marker)
417       .removeLayer(endpoints[1].marker);
418   };
419
420   return page;
421 };
422
423 OSM.Directions.engines = [];
424
425 OSM.Directions.addEngine = function (engine, supportsHTTPS) {
426   if (document.location.protocol === "http:" || supportsHTTPS) {
427     OSM.Directions.engines.push(engine);
428   }
429 };