]> git.openstreetmap.org Git - rails.git/blob - app/assets/javascripts/routing_engines/osrm.js
Merge pull request #18 from danstowell/jsrouting-durationcalc
[rails.git] / app / assets / javascripts / routing_engines / osrm.js
1 // OSRM car engine
2 // Doesn't yet support hints
3
4 OSRMEngine = function(vehicleName, baseURL, locale) {
5     this.vehicleName = vehicleName;
6     this.baseURL = baseURL;
7     this.locale = locale;
8     if (!locale)
9         this.locale = "en";
10 };
11
12 OSRMEngine.prototype.createConfig = function() {
13     var that = this;
14     return {
15         name: "javascripts.directions.engines.osrm_"+this.vehicleName.toLowerCase(),
16         creditline: 'Directions courtesy of <a href="http://project-osrm.org/" target="_blank">OSRM</a>',
17         draggable: true,
18         _hints: {},
19         getRoute: function(isFinal,points) {
20             var url=that.baseURL+"?z=14&output=json";
21             for (var i=0; i<points.length; i++) {
22                 var pair=points[i].join(',');
23                 url+="&loc="+pair;
24                 if (this._hints[pair]) url+= "&hint="+this._hints[pair];
25             }
26             if (isFinal) url+="&instructions=true";
27             this.requestCORS(url);
28         },
29         gotRoute: function(router,data) {
30             if (data.status==207) {
31                 return false;
32             }
33             // Draw polyline
34             var line=L.PolylineUtil.decode(data.route_geometry);
35             for (i=0; i<line.length; i++) { line[i].lat/=10; line[i].lng/=10; }
36             router.setPolyline(line);
37             // Assemble instructions
38             var steps=[];
39             for (i=0; i<data.route_instructions.length; i++) {
40                 var s=data.route_instructions[i];
41                 var linesegend;
42                 var instCodes=s[0].split('-');
43                 var instText="<b>"+(i+1)+".</b> ";
44                 instText+=TURN_INSTRUCTIONS[instCodes[0]];
45                 if (instCodes[1]) { instText+="exit "+instCodes[1]+" "; }
46                 if (instCodes[0]!=15) { instText+=s[1] ? "<b>"+s[1]+"</b>" : I18n.t('javascripts.directions.instructions.unnamed'); }
47                 if ((i+1)<data.route_instructions.length) {
48                     linesegend = data.route_instructions[i+1][3] + 1;
49                 } else {
50                     linesegend = s[3] + 1;
51                 }
52                 steps.push([line[s[3]], s[0].split('-')[0], instText, s[2], line.slice(s[3], linesegend)]);
53             }
54             if (steps.length) router.setItinerary({ steps: steps, distance: data.route_summary.total_distance, time: data.route_summary.total_time });
55             return true;
56         }
57     };
58 };
59
60 OSM.RoutingEngines.add(false, new OSRMEngine("Car", "http://router.project-osrm.org/viaroute").createConfig());