]> git.openstreetmap.org Git - rails.git/blob - app/assets/javascripts/index/directions.js
Pass viewbox to Nominatim when geocoding routing endpoints
[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 from = endpoints[0].latlng,
145         to = endpoints[1].latlng;
146
147     OSM.router.route("/directions?" + querystring.stringify({
148       from: $("#route_to").val(),
149       to: $("#route_from").val(),
150       route: to.lat + "," + to.lng + ";" + from.lat + "," + from.lng
151     }));
152   });
153
154   $(".directions_form .close").on("click", function (e) {
155     e.preventDefault();
156     var route_from = endpoints[0].value;
157     if (route_from) {
158       OSM.router.route("/?query=" + encodeURIComponent(route_from) + OSM.formatHash(map));
159     } else {
160       OSM.router.route("/" + OSM.formatHash(map));
161     }
162   });
163
164   function formatDistance(m) {
165     if (m < 1000) {
166       return Math.round(m) + "m";
167     } else if (m < 10000) {
168       return (m / 1000.0).toFixed(1) + "km";
169     } else {
170       return Math.round(m / 1000) + "km";
171     }
172   }
173
174   function formatTime(s) {
175     var m = Math.round(s / 60);
176     var h = Math.floor(m / 60);
177     m -= h * 60;
178     return h + ":" + (m < 10 ? "0" : "") + m;
179   }
180
181   function findEngine(id) {
182     return engines.findIndex(function (engine) {
183       return engine.id === id;
184     });
185   }
186
187   function setEngine(index) {
188     chosenEngine = engines[index];
189     select.val(index);
190   }
191
192   function getRoute(fitRoute, reportErrors) {
193     // Cancel any route that is already in progress
194     if (awaitingRoute) awaitingRoute.abort();
195
196     // go fetch geocodes for any endpoints which have not already
197     // been geocoded.
198     for (var ep_i = 0; ep_i < 2; ++ep_i) {
199       var endpoint = endpoints[ep_i];
200       if (!endpoint.hasGeocode && !endpoint.awaitingGeocode) {
201         endpoint.getGeocode();
202         awaitingGeocode = true;
203       }
204     }
205     if (endpoints[0].awaitingGeocode || endpoints[1].awaitingGeocode) {
206       awaitingGeocode = true;
207       return;
208     }
209
210     var o = endpoints[0].latlng,
211         d = endpoints[1].latlng;
212
213     if (!o || !d) return;
214     $("header").addClass("closed");
215
216     var precision = OSM.zoomPrecision(map.getZoom());
217
218     OSM.router.replace("/directions?" + querystring.stringify({
219       engine: chosenEngine.id,
220       route: o.lat.toFixed(precision) + "," + o.lng.toFixed(precision) + ";" +
221              d.lat.toFixed(precision) + "," + d.lng.toFixed(precision)
222     }));
223
224     // copy loading item to sidebar and display it. we copy it, rather than
225     // just using it in-place and replacing it in case it has to be used
226     // again.
227     $("#sidebar_content").html($(".directions_form .loader_copy").html());
228     map.setSidebarOverlaid(false);
229
230     awaitingRoute = chosenEngine.getRoute([o, d], function (err, route) {
231       awaitingRoute = null;
232
233       if (err) {
234         map.removeLayer(polyline);
235
236         if (reportErrors) {
237           $("#sidebar_content").html("<p class=\"search_results_error\">" + I18n.t("javascripts.directions.errors.no_route") + "</p>");
238         }
239
240         return;
241       }
242
243       polyline
244         .setLatLngs(route.line)
245         .addTo(map);
246
247       if (fitRoute) {
248         map.fitBounds(polyline.getBounds().pad(0.05));
249       }
250
251       var html = "<h2><a class=\"geolink\" href=\"#\">" +
252         "<span class=\"icon close\"></span></a>" + I18n.t("javascripts.directions.directions") +
253         "</h2><p id=\"routing_summary\">" +
254         I18n.t("javascripts.directions.distance") + ": " + formatDistance(route.distance) + ". " +
255         I18n.t("javascripts.directions.time") + ": " + formatTime(route.time) + ".";
256       if (typeof route.ascend !== "undefined" && typeof route.descend !== "undefined") {
257         html += "<br />" +
258           I18n.t("javascripts.directions.ascend") + ": " + Math.round(route.ascend) + "m. " +
259           I18n.t("javascripts.directions.descend") + ": " + Math.round(route.descend) + "m.";
260       }
261       html += "</p><table id=\"turnbyturn\" />";
262
263       $("#sidebar_content")
264         .html(html);
265
266       // Add each row
267       route.steps.forEach(function (step) {
268         var ll = step[0],
269             direction = step[1],
270             instruction = step[2],
271             dist = step[3],
272             lineseg = step[4];
273
274         if (dist < 5) {
275           dist = "";
276         } else if (dist < 200) {
277           dist = String(Math.round(dist / 10) * 10) + "m";
278         } else if (dist < 1500) {
279           dist = String(Math.round(dist / 100) * 100) + "m";
280         } else if (dist < 5000) {
281           dist = String(Math.round(dist / 100) / 10) + "km";
282         } else {
283           dist = String(Math.round(dist / 1000)) + "km";
284         }
285
286         var row = $("<tr class='turn'/>");
287         row.append("<td><div class='direction i" + direction + "'/></td> ");
288         row.append("<td class='instruction'>" + instruction);
289         row.append("<td class='distance'>" + dist);
290
291         row.on("click", function () {
292           popup
293             .setLatLng(ll)
294             .setContent("<p>" + instruction + "</p>")
295             .openOn(map);
296         });
297
298         row.hover(function () {
299           highlight
300             .setLatLngs(lineseg)
301             .addTo(map);
302         }, function () {
303           map.removeLayer(highlight);
304         });
305
306         $("#turnbyturn").append(row);
307       });
308
309       $("#sidebar_content").append("<p id=\"routing_credit\">" +
310         I18n.t("javascripts.directions.instructions.courtesy", { link: chosenEngine.creditline }) +
311         "</p>");
312
313       $("#sidebar_content a.geolink").on("click", function (e) {
314         e.preventDefault();
315         map.removeLayer(polyline);
316         $("#sidebar_content").html("");
317         map.setSidebarOverlaid(true);
318         // TODO: collapse width of sidebar back to previous
319       });
320     });
321   }
322
323   var chosenEngineIndex = findEngine("fossgis_osrm_car");
324   if ($.cookie("_osm_directions_engine")) {
325     chosenEngineIndex = findEngine($.cookie("_osm_directions_engine"));
326   }
327   setEngine(chosenEngineIndex);
328
329   select.on("change", function (e) {
330     chosenEngine = engines[e.target.selectedIndex];
331     $.cookie("_osm_directions_engine", chosenEngine.id, { expires: expiry, path: "/" });
332     if (map.hasLayer(polyline)) {
333       getRoute(true, true);
334     }
335   });
336
337   $(".directions_form").on("submit", function (e) {
338     e.preventDefault();
339     getRoute(true, true);
340   });
341
342   $(".routing_marker").on("dragstart", function (e) {
343     var dt = e.originalEvent.dataTransfer;
344     dt.effectAllowed = "move";
345     var dragData = { type: $(this).data("type") };
346     dt.setData("text", JSON.stringify(dragData));
347     if (dt.setDragImage) {
348       var img = $("<img>").attr("src", $(e.originalEvent.target).attr("src"));
349       dt.setDragImage(img.get(0), 12, 21);
350     }
351   });
352
353   var page = {};
354
355   page.pushstate = page.popstate = function () {
356     $(".search_form").hide();
357     $(".directions_form").show();
358
359     $("#map").on("dragend dragover", function (e) {
360       e.preventDefault();
361     });
362
363     $("#map").on("drop", function (e) {
364       e.preventDefault();
365       var oe = e.originalEvent;
366       var dragData = JSON.parse(oe.dataTransfer.getData("text"));
367       var type = dragData.type;
368       var pt = L.DomEvent.getMousePosition(oe, map.getContainer()); // co-ordinates of the mouse pointer at present
369       pt.y += 20;
370       var ll = map.containerPointToLatLng(pt);
371       endpoints[type === "from" ? 0 : 1].setLatLng(ll);
372       getRoute(true, true);
373     });
374
375     var params = querystring.parse(location.search.substring(1)),
376         route = (params.route || "").split(";"),
377         from = route[0] && L.latLng(route[0].split(",")),
378         to = route[1] && L.latLng(route[1].split(","));
379
380     if (params.engine) {
381       var engineIndex = findEngine(params.engine);
382
383       if (engineIndex >= 0) {
384         setEngine(engineIndex);
385       }
386     }
387
388     endpoints[0].setValue(params.from || "", from);
389     endpoints[1].setValue(params.to || "", to);
390
391     map.setSidebarOverlaid(!from || !to);
392
393     getRoute(true, true);
394   };
395
396   page.load = function () {
397     page.pushstate();
398   };
399
400   page.unload = function () {
401     $(".search_form").show();
402     $(".directions_form").hide();
403     $("#map").off("dragend dragover drop");
404
405     map
406       .removeLayer(popup)
407       .removeLayer(polyline)
408       .removeLayer(endpoints[0].marker)
409       .removeLayer(endpoints[1].marker);
410   };
411
412   return page;
413 };
414
415 OSM.Directions.engines = [];
416
417 OSM.Directions.addEngine = function (engine, supportsHTTPS) {
418   if (document.location.protocol === "http:" || supportsHTTPS) {
419     OSM.Directions.engines.push(engine);
420   }
421 };