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