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