]> git.openstreetmap.org Git - rails.git/blob - app/assets/javascripts/index/directions/graphhopper.js
e1e8a986195dca70681c1be324298947a455c904
[rails.git] / app / assets / javascripts / index / directions / graphhopper.js
1 (function () {
2   function GraphHopperEngine(modeId, vehicleType) {
3     const GH_INSTR_MAP = {
4       "-3": "sharp-left",
5       "-2": "left",
6       "-1": "slight-left",
7       "0": "straight",
8       "1": "slight-right",
9       "2": "right",
10       "3": "sharp-right",
11       "4": "destination", // finish reached
12       "5": "destination", // via reached
13       "6": "roundabout",
14       "-7": "fork-left",
15       "7": "fork-right",
16       "-98": "u-turn-left", // unknown direction u-turn
17       "-8": "u-turn-left", // left u-turn
18       "8": "u-turn-right" // right u-turn
19     };
20
21     function _processDirections(path) {
22       const line = L.PolylineUtil.decode(path.points);
23
24       const steps = path.instructions.map(function (instr) {
25         const lineseg = line
26           .slice(instr.interval[0], instr.interval[1] + 1)
27           .map(([lat, lng]) => ({ lat, lng }));
28         return [
29           lineseg[0],
30           GH_INSTR_MAP[instr.sign],
31           instr.text,
32           instr.distance,
33           lineseg
34         ];
35       });
36       steps.at(-1)[1] = "destination";
37
38       return {
39         line: line,
40         steps: steps,
41         distance: path.distance,
42         time: path.time / 1000,
43         ascend: path.ascend,
44         descend: path.descend
45       };
46     }
47
48     return {
49       mode: modeId,
50       provider: "graphhopper",
51       creditline: "<a href=\"https://www.graphhopper.com/\" target=\"_blank\">GraphHopper</a>",
52       draggable: false,
53
54       getRoute: function (points, signal) {
55         // GraphHopper Directions API documentation
56         // https://graphhopper.com/api/1/docs/routing/
57         const query = new URLSearchParams({
58           vehicle: vehicleType,
59           locale: OSM.i18n.locale,
60           key: "LijBPDQGfu7Iiq80w3HzwB4RUDJbMbhs6BU0dEnn",
61           elevation: false,
62           instructions: true,
63           turn_costs: vehicleType === "car"
64         });
65         points.forEach(p => query.append("point", p.lat + "," + p.lng));
66         return fetch(OSM.GRAPHHOPPER_URL + "?" + query, { signal })
67           .then(response => response.json())
68           .then(({ paths }) => {
69             if (!paths || paths.length === 0) throw new Error();
70             return _processDirections(paths[0]);
71           });
72       }
73     };
74   }
75
76   OSM.Directions.addEngine(new GraphHopperEngine("car", "car"), true);
77   OSM.Directions.addEngine(new GraphHopperEngine("bicycle", "bike"), true);
78   OSM.Directions.addEngine(new GraphHopperEngine("foot", "foot"), true);
79 }());