]> git.openstreetmap.org Git - rails.git/blob - app/assets/javascripts/index/directions/graphhopper.js
Attach routing credit to route
[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(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       steps.at(-1)[0] = "destination";
31
32       return {
33         line,
34         steps,
35         distance: path.distance,
36         time: path.time / 1000,
37         ascend: path.ascend,
38         descend: path.descend,
39         credit: "GraphHopper",
40         creditlink: "https://www.graphhopper.com/"
41       };
42     }
43
44     return {
45       mode: modeId,
46       provider: "graphhopper",
47       draggable: false,
48
49       getRoute: function (points, signal) {
50         // GraphHopper Directions API documentation
51         // https://graphhopper.com/api/1/docs/routing/
52         const query = new URLSearchParams({
53           vehicle: vehicleType,
54           locale: OSM.i18n.locale,
55           key: "LijBPDQGfu7Iiq80w3HzwB4RUDJbMbhs6BU0dEnn",
56           elevation: false,
57           instructions: true,
58           turn_costs: vehicleType === "car"
59         });
60         points.forEach(p => query.append("point", p.lat + "," + p.lng));
61         return fetch(OSM.GRAPHHOPPER_URL + "?" + query, { signal })
62           .then(response => response.json())
63           .then(({ paths }) => {
64             if (!paths || paths.length === 0) throw new Error();
65             return _processDirections(paths[0]);
66           });
67       }
68     };
69   }
70
71   OSM.Directions.addEngine(new GraphHopperEngine("car", "car"), true);
72   OSM.Directions.addEngine(new GraphHopperEngine("bicycle", "bike"), true);
73   OSM.Directions.addEngine(new GraphHopperEngine("foot", "foot"), true);
74 }());