]> git.openstreetmap.org Git - rails.git/blob - app/assets/javascripts/index/directions/graphhopper.js
Merge remote-tracking branch 'upstream/pull/6913'
[rails.git] / app / assets / javascripts / index / directions / graphhopper.js
1 (function () {
2   function GraphHopperEngine(modeId, vehicleType, profile) {
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(instr => [
25         GH_INSTR_MAP[instr.sign],
26         instr.text,
27         instr.distance,
28         line.slice(instr.interval[0], instr.interval[1] + 1)
29       ]);
30
31       steps.at(-1)[0] = "destination";
32
33       return {
34         line,
35         steps,
36         distance: path.distance,
37         time: path.time / 1000,
38         ascend: path.ascend,
39         descend: path.descend
40       };
41     }
42
43     return {
44       mode: modeId,
45       provider: "graphhopper",
46       draggable: false,
47
48       getRoute: function (points, signal) {
49         // GraphHopper Directions API documentation https://docs.graphhopper.com
50         const query = new URLSearchParams({
51           profile: vehicleType,
52           locale: OSM.i18n.locale,
53           key: "7cb4eb19-e0f4-40a3-a5e0-f2c039366f32",
54           elevation: false,
55           instructions: true
56         });
57         const demoQuery = new URLSearchParams({ profile });
58
59         for (const { lat, lng } of points) {
60           query.append("point", [lat, lng]);
61           demoQuery.append("point", [lat, lng]);
62         }
63
64         const meta = {
65           credit: "GraphHopper",
66           creditlink: "https://www.graphhopper.com/",
67           demolink: "https://graphhopper.com/maps/?" + demoQuery
68         };
69
70         return fetch(OSM.GRAPHHOPPER_URL + "?" + query, { signal })
71           .then(response => response.json())
72           .then(({ paths }) => {
73             if (!paths || paths.length === 0) throw new Error();
74
75             return { ..._processDirections(paths[0]), ...meta };
76           });
77       }
78     };
79   }
80
81   OSM.Directions.addEngine(new GraphHopperEngine("car", "car", "car"), true);
82   OSM.Directions.addEngine(new GraphHopperEngine("bicycle", "bike", "bike"), true);
83   OSM.Directions.addEngine(new GraphHopperEngine("foot", "foot", "foot"), true);
84 }());