]> git.openstreetmap.org Git - rails.git/blob - app/assets/javascripts/index/directions.js.erb
Rename directions_engines to directions
[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
167     var precision = OSM.zoomPrecision(map.getZoom());
168
169     OSM.router.replace("/directions?" + querystring.stringify({
170       engine: chosenEngine.id,
171       route: o.lat.toFixed(precision) + ',' + o.lng.toFixed(precision) + ';' +
172              d.lat.toFixed(precision) + ',' + d.lng.toFixed(precision)
173     }));
174
175     // copy loading item to sidebar and display it. we copy it, rather than
176     // just using it in-place and replacing it in case it has to be used
177     // again.
178     $('#sidebar_content').html($('.directions_form .loader_copy').html());
179     awaitingRoute = true;
180     map.setSidebarOverlaid(false);
181
182     chosenEngine.getRoute([o, d], function (err, route) {
183       awaitingRoute = false;
184
185       if (err) {
186         map.removeLayer(polyline);
187
188         if (!dragging) {
189           alert(I18n.t('javascripts.directions.errors.no_route'));
190         }
191
192         return;
193       }
194
195       polyline
196         .setLatLngs(route.line)
197         .addTo(map);
198
199       if (!dragging) {
200         map.fitBounds(polyline.getBounds().pad(0.05));
201       }
202
203       var html = '<h2><a class="geolink" href="#">' +
204         '<span class="icon close"></span></a>' + I18n.t('javascripts.directions.directions') +
205         '</h2><p id="routing_summary">' +
206         I18n.t('javascripts.directions.distance') + ': ' + formatDistance(route.distance) + '. ' +
207         I18n.t('javascripts.directions.time') + ': ' + formatTime(route.time) + '.</p>' +
208         '<table id="turnbyturn" />';
209
210       $('#sidebar_content')
211         .html(html);
212
213       // Add each row
214       var cumulative = 0;
215       route.steps.forEach(function (step) {
216         var ll        = step[0],
217           direction   = step[1],
218           instruction = step[2],
219           dist        = step[3],
220           lineseg     = step[4];
221
222         cumulative += dist;
223
224         if (dist < 5) {
225           dist = "";
226         } else if (dist < 200) {
227           dist = Math.round(dist / 10) * 10 + "m";
228         } else if (dist < 1500) {
229           dist = Math.round(dist / 100) * 100 + "m";
230         } else if (dist < 5000) {
231           dist = Math.round(dist / 100) / 10 + "km";
232         } else {
233           dist = Math.round(dist / 1000) + "km";
234         }
235
236         var row = $("<tr class='turn'/>");
237         row.append("<td><div class='direction i" + direction + "'/></td> ");
238         row.append("<td class='instruction'>" + instruction);
239         row.append("<td class='distance'>" + dist);
240
241         row.on('click', function () {
242           popup
243             .setLatLng(ll)
244             .setContent("<p>" + instruction + "</p>")
245             .openOn(map);
246         });
247
248         row.hover(function () {
249           highlight
250             .setLatLngs(lineseg)
251             .addTo(map);
252         }, function () {
253           map.removeLayer(highlight);
254         });
255
256         $('#turnbyturn').append(row);
257       });
258
259       $('#sidebar_content').append('<p id="routing_credit">' +
260         I18n.t('javascripts.directions.instructions.courtesy', {link: chosenEngine.creditline}) +
261         '</p>');
262
263       $('#sidebar_content a.geolink').on('click', function(e) {
264         e.preventDefault();
265         map.removeLayer(polyline);
266         $('#sidebar_content').html('');
267         map.setSidebarOverlaid(true);
268         // TODO: collapse width of sidebar back to previous
269       });
270     });
271   }
272
273   var engines = OSM.Directions.engines;
274
275   engines.sort(function (a, b) {
276     a = I18n.t('javascripts.directions.engines.' + a.id);
277     b = I18n.t('javascripts.directions.engines.' + b.id);
278     return a.localeCompare(b);
279   });
280
281   var select = $('select.routing_engines');
282
283   engines.forEach(function(engine, i) {
284     select.append("<option value='" + i + "'>" + I18n.t('javascripts.directions.engines.' + engine.id) + "</option>");
285   });
286
287   setEngine('osrm_car');
288
289   select.on("change", function (e) {
290     chosenEngine = engines[e.target.selectedIndex];
291     if (map.hasLayer(polyline)) {
292       getRoute();
293     }
294   });
295
296   $(".directions_form").on("submit", function(e) {
297     e.preventDefault();
298     $("header").addClass("closed");
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 };