8d01bcd169dd06c691faf849f9d3e2ab1aab260a
[rails.git] / app / assets / javascripts / index / directions / graphhopper.js
1 function GraphHopperEngine(id, vehicleParam) {
2   var GH_INSTR_MAP = {
3     "-3": 6, // sharp left
4     "-2": 7, // left
5     "-1": 8, // slight left
6     0: 0, // straight
7     1: 1, // slight right
8     2: 2, // right
9     3: 3, // sharp right
10     4: -1, // finish reached
11     5: -1 // via reached
12   };
13
14   return {
15     id: id,
16     creditline: '<a href="https://graphhopper.com/" target="_blank">Graphhopper</a>',
17     draggable: false,
18
19     getRoute: function (points, callback) {
20       // documentation
21       // https://github.com/graphhopper/graphhopper/blob/master/docs/web/api-doc.md
22       var url = "https://graphhopper.com/api/1/route?"
23         + vehicleParam
24         + "&locale=" + I18n.currentLocale()
25         + "&key=LijBPDQGfu7Iiq80w3HzwB4RUDJbMbhs6BU0dEnn"
26         + "&type=jsonp"
27         + "&instructions=true";
28
29       for (var i = 0; i < points.length; i++) {
30         url += "&point=" + points[i].lat + ',' + points[i].lng;
31       }
32
33       $.ajax({
34         url: url,
35         dataType: 'jsonp',
36         success: function (data) {
37           if (!data.paths || data.paths.length == 0)
38             return callback(true);
39
40           var path = data.paths[0];
41           var line = L.PolylineUtil.decode(path.points);
42
43           var steps = [];
44           var len = path.instructions.length;
45           for (var i = 0; i < len; i++) {
46             var instr = path.instructions[i];
47             var instrCode = (i === len - 1) ? 15 : GH_INSTR_MAP[instr.sign];
48             var instrText = "<b>" + (i + 1) + ".</b> ";
49             instrText += instr.text;
50             var latLng = line[instr.interval[0]];
51             var distInMeter = instr.distance;
52             steps.push([
53               {lat: latLng.lat, lng: latLng.lng},
54               instrCode,
55               instrText,
56               distInMeter,
57               []
58             ]); // TODO does graphhopper map instructions onto line indices?
59           }
60
61           callback(null, {
62             line: line,
63             steps: steps,
64             distance: path.distance,
65             time: path.time / 1000
66           });
67         }
68       });
69     }
70   };
71 }
72
73 OSM.Directions.addEngine(GraphHopperEngine("graphhopper_bicycle", "vehicle=bike"), false);
74 OSM.Directions.addEngine(GraphHopperEngine("graphhopper_foot", "vehicle=foot"), false);