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