]> git.openstreetmap.org Git - rails.git/blob - app/assets/javascripts/index/directions.js.erb
Refactor
[rails.git] / app / assets / javascripts / index / directions.js.erb
1 //= require_self
2 //= require_tree ./directions_engines
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       r.requestRoute(!dragging, false);
50     });
51
52     input.on("change", function (e) {
53       endpoint.awaitingGeocode = true;
54
55       $.getJSON('<%= NOMINATIM_URL %>search?q=' + encodeURIComponent(e.target.value) + '&format=json', function (json) {
56         endpoint.awaitingGeocode = false;
57
58         if (json.length == 0) {
59           alert(I18n.t('javascripts.directions.errors.no_place'));
60           return;
61         }
62
63         input.val(json[0].display_name);
64
65         endpoint.latlng = L.latLng(json[0]);
66         endpoint.marker
67           .setLatLng(endpoint.latlng)
68           .addTo(map);
69
70         if (awaitingGeocode) {
71           awaitingGeocode = false;
72           r.requestRoute(true, true);
73         }
74       });
75     });
76
77     endpoint.setLatLng = function (ll) {
78       input.val(Math.round(ll.lat * 10000) / 10000 + " " + Math.round(ll.lng * 10000) / 10000);
79       endpoint.latlng = ll;
80       endpoint.marker
81         .setLatLng(ll)
82         .addTo(map);
83     };
84
85     return endpoint;
86   }
87
88   function formatDistance(m) {
89     if (m < 1000) {
90       return Math.round(m) + "m";
91     } else if (m < 10000) {
92       return (m / 1000.0).toFixed(1) + "km";
93     } else {
94       return Math.round(m / 1000) + "km";
95     }
96   }
97
98   function formatTime(s) {
99     var m = Math.round(s / 60);
100     var h = Math.floor(m / 60);
101     m -= h * 60;
102     return h + ":" + (m < 10 ? '0' : '') + m;
103   }
104
105   var engines = OSM.Directions.engines;
106
107   engines.sort(function (a, b) {
108     return I18n.t(a.name) > I18n.t(b.name);
109   });
110
111   var select = $('select.routing_engines');
112
113   for (var i = 0; i < engines.length; i++) {
114     var engine = engines[i];
115
116     select.append("<option value='" + i + "'>" + I18n.t(engine.name) + "</option>");
117
118     if (engine.name == 'javascripts.directions.engines.osrm_car') {
119       chosenEngine = engine;
120       select.val(i);
121     }
122   }
123
124   select.on("change", function (e) {
125     chosenEngine = engines[e.target.selectedIndex];
126     if (map.hasLayer(polyline)) { // and if a route is currently showing, must also refresh, else confusion
127       r.requestRoute(true, false);
128     }
129   });
130
131   $(".get_directions").on("click", function (e) {
132     e.preventDefault();
133     $(".search").hide();
134     $(".routing").show();
135     $(".search_form input[type='submit']").addClass("routing_submit");
136     $(".query_wrapper.routing [name=route_from]").focus();
137
138     $("#map").on('dragend dragover', function (e) {
139       e.preventDefault();
140     });
141
142     $("#map").on('drop', function (e) {
143       e.preventDefault();
144       var oe = e.originalEvent;
145       var id = oe.dataTransfer.getData('id');
146       var pt = L.DomEvent.getMousePosition(oe, map.getContainer());  // co-ordinates of the mouse pointer at present
147       pt.x += Number(oe.dataTransfer.getData('offsetX'));
148       pt.y += Number(oe.dataTransfer.getData('offsetY'));
149       var ll = map.containerPointToLatLng(pt);
150       endpoints[id === 'marker_from' ? 0 : 1].setLatLng(ll);
151       r.requestRoute(true, false);
152     });
153
154     $(".routing_marker").on('dragstart', function (e) {
155       e.originalEvent.dataTransfer.effectAllowed = 'move';
156       e.originalEvent.dataTransfer.setData('id', this.id);
157       var xo = e.originalEvent.clientX - $(e.target).offset().left;
158       var yo = e.originalEvent.clientY - $(e.target).offset().top;
159       e.originalEvent.dataTransfer.setData('offsetX', e.originalEvent.target.width / 2 - xo);
160       e.originalEvent.dataTransfer.setData('offsetY', e.originalEvent.target.height - yo);
161     });
162   });
163
164   $(".close_directions").on("click", function (e) {
165     e.preventDefault();
166     $(".search").show();
167     $(".routing").hide();
168     $(".search_form input[type='submit']").removeClass("routing_submit");
169     $("#content").addClass("overlay-sidebar");
170     $(".query_wrapper.routing input").val("");
171     map
172       .removeLayer(popup)
173       .removeLayer(polyline)
174       .removeLayer(endpoints[0].marker)
175       .removeLayer(endpoints[1].marker);
176     endpoints[0].latlng = endpoints[1].latlng = null;
177     $("#map").off('dragend drop dragover');
178     $(".routing_marker").off('dragstart');
179     $(".query_wrapper.search [name=query]").focus();
180   });
181
182   var r = {};
183
184   r.requestRoute = function (isFinal, updateZoom) {
185     if (endpoints[0].awaitingGeocode || endpoints[1].awaitingGeocode) {
186       awaitingGeocode = true;
187       return;
188     }
189
190     var origin = endpoints[0].latlng,
191       destination = endpoints[1].latlng;
192
193     if (!origin || !destination) {
194       return;
195     }
196
197     $(".query_wrapper.routing .spinner").show();
198     awaitingRoute = true;
199
200     if (updateZoom) {
201       map.fitBounds(L.latLngBounds(origin, destination).pad(0.05));
202     }
203
204     chosenEngine.getRoute(isFinal, [origin, destination], function (err, route) {
205       awaitingRoute = false;
206
207       $(".query_wrapper.routing .spinner").hide();
208
209       if (err) {
210         map.removeLayer(polyline);
211
212         if (!dragging) {
213           alert(I18n.t('javascripts.directions.errors.no_route'));
214         }
215
216         return;
217       }
218
219       polyline
220         .setLatLngs(route.line)
221         .addTo(map);
222
223       $("#content").removeClass("overlay-sidebar");
224
225       var html = ('<h2><a class="geolink" href="#" onclick="$(~.close_directions~).click();return false;">' +
226         '<span class="icon close"></span></a>' + I18n.t('javascripts.directions.directions') +
227         '</h2><p id="routing_summary">' +
228         I18n.t('javascripts.directions.distance') + ': ' + formatDistance(route.distance) + '. ' +
229         I18n.t('javascripts.directions.time') + ': ' + formatTime(route.time) + '.</p>' +
230         '<table id="turnbyturn" />').replace(/~/g, "'");
231
232       $('#sidebar_content')
233         .html(html);
234
235       // Add each row
236       var cumulative = 0;
237       route.steps.forEach(function (step) {
238         var ll        = step[0],
239           direction   = step[1],
240           instruction = step[2],
241           dist        = step[3],
242           lineseg     = step[4];
243
244         cumulative += dist;
245
246         if (dist < 5) {
247           dist = "";
248         } else if (dist < 200) {
249           dist = Math.round(dist / 10) * 10 + "m";
250         } else if (dist < 1500) {
251           dist = Math.round(dist / 100) * 100 + "m";
252         } else if (dist < 5000) {
253           dist = Math.round(dist / 100) / 10 + "km";
254         } else {
255           dist = Math.round(dist / 1000) + "km";
256         }
257
258         var row = $("<tr class='turn'/>");
259         row.append("<td class='direction i" + direction + "'> ");
260         row.append("<td class='instruction'>" + instruction);
261         row.append("<td class='distance'>" + dist);
262
263         row.on('click', function () {
264           popup
265             .setLatLng(ll)
266             .setContent("<p>" + instruction + "</p>")
267             .openOn(map);
268         });
269
270         row.hover(function () {
271           highlight
272             .setLatLngs(lineseg)
273             .addTo(map);
274         }, function () {
275           map.removeLayer(highlight);
276         });
277
278         $('#turnbyturn').append(row);
279       });
280
281       $('#sidebar_content').append('<p id="routing_credit">' +
282         I18n.t('javascripts.directions.instructions.courtesy', {link: chosenEngine.creditline}) +
283         '</p>');
284     });
285   };
286
287   return r;
288 };
289
290 OSM.Directions.engines = [];
291
292 OSM.Directions.addEngine = function (engine, supportsHTTPS) {
293   if (document.location.protocol == "http:" || supportsHTTPS) {
294     OSM.Directions.engines.push(engine);
295   }
296 };