PageSourceSearch

https://mapa.info.pl/L.Routing.TomTom.js

js mapa.info.pl collected 2026-10-02 12:31:22 UTC 11,375 bytes, 301 lines download raw bytes

1(function() {
2    'use strict';
3
4    //var L = require('leaflet');
5    //var corslite = require('corslite');
6
7    L.Routing = L.Routing || {};
8
9    L.Routing.TomTom = L.Class.extend({
10        options: {
11            serviceUrl: "https://api.tomtom.com/routing/1/calculateRoute",
12            timeout: 30 * 1000,
13            routeType: "fastest", // fastest, shortest, eco, thrilling
14            language: "pl-PL", // en-GB
15            instructionsType: "text", // coded, text, tagged
16            traffic: true,
17            avoid: "", // [tollRoads, motorways, ferries, unpavedRoads, carpools, alreadyUsedRoads]
18            travelMode: "car", // car, truck, taxi, bus, van, motorcycle, bicycle, pedestrian
19            vehicleMaxSpeed: 0, // km/h
20            vehicleWeight: 0, // kg
21            vehicleAxleWeight: 0, // kg
22            vehicleLength: 0, // m
23            vehicleWidth: 0, // m
24            vehicleHeight: 0, // m
25            departAt: "", // YYYY-MM-DD\THH:mm:ss
26            arriveAt: "", // YYYY-MM-DD\THH:mm:ss
27            vehicleCommercial: false
28        },
29
30        initialize: function(apiKey, options) {
31            this._apiKey = apiKey;
32            L.Util.setOptions(this, options);
33        },
34
35        route: function(waypoints, callback, context, options) {
36            var timedOut = false,
37                wps = [],
38                url,
39                timer,
40                wp,
41                i;
42
43            options = options || {};
44            url = this.buildRouteUrl(waypoints, options);
45
46            timer = setTimeout(function() {
47                                timedOut = true;
48                                callback.call(context || callback, {
49                                    status: -1,
50                                    message: 'TomTom request timed out.'
51                                });
52                            }, this.options.timeout);
53
54            // Create a copy of the waypoints, since they
55            // might otherwise be asynchronously modified while
56            // the request is being processed.
57            for (i = 0; i < waypoints.length; i++) {
58                wp = waypoints[i];
59                wps.push({
60                    latLng: wp.latLng,
61                    name: wp.name,
62                    options: wp.options
63                });
64            }
65
66            corslite(url, L.bind(function(err, resp) {
67                var data;
68
69                clearTimeout(timer);
70                if (!timedOut) {
71                    if (!err) {
72                        data = JSON.parse(resp.responseText);
73                        this._routeDone(data, wps, callback, context);
74                    } else {
75                        callback.call(context || callback, {
76                            status: -1,
77                            message: 'HTTP request failed: ' + JSON.parse(err.responseText).error.description
78                        });
79                    }
80                }
81            }, this));
82
83            return this;
84        },
85
86        _routeDone: function(response, inputWaypoints, callback, context) {
87            var alts = [],
88                mappedWaypoints,
89                coordinates = [],
90                i,
91                path,
92                summary = [],
93                instructions,
94                index = 0;
95
96            context = context || callback;
97            if (response.error && response.error.description) {
98                callback.call(context, {
99                    status: -1,
100                    message: response.error.description
101                });
102                return;
103            }
104	    
105
106            for (i = 0; i < response.routes[0].legs.length; i++) {
107	        //console.log(response.routes[0].guidance);
108                path = response.routes[0].legs[i];
109                coordinates = coordinates.concat(this._decodePolyline(path.points));
110                index += (path.points.length - 1);
111                summary.push({ summary: path.summary, index: index });
112            }
113
114	    //console.log(response.routes[0].guidance.instructions);
115	    var results = [],  i, j;
116            var waypoints=[];  
117	 
118            for (i = 0; i < response.routes[0].guidance.instructions.length; i++) 
119            {
120		for (j = 0; j < coordinates.length; j++) 
121	        {
122
123		   if (coordinates[j].lat==response.routes[0].guidance.instructions[i].point.latitude && coordinates[j].lng==response.routes[0].guidance.instructions[i].point.longitude)
124		   {
125	                results.push({ time: response.routes[0].guidance.instructions[i].travelTimeInSeconds,
126	                distance: response.routes[0].guidance.instructions[i].routeOffsetInMeters,
127	  	      //type: response.routes[0].guidance.instructions[i].instructionType,
128		      //road: response.routes[0].guidance.instructions[i].street,
129                             text: response.routes[0].guidance.instructions[i].message,
130		      
131                             index: j
132				});
133		      break;
134	            }
135		}
136
137		//waypoints.push({latLng: new L.latLng(response.routes[0].guidance.instructions[i].point.latitude, response.routes[0].guidance.instructions[i].point.longitude), name: 'aa'});
138
139            }
140
141           
142
143
144
145
146	    console.log(results);
147            instructions = results;
148            mappedWaypoints = this._mapWaypointIndices(inputWaypoints, instructions, coordinates);
149            console.log(waypoints);          
150            console.log(mappedWaypoints);   
151            alts = [{
152                name: '',
153                coordinates: coordinates,
154                instructions: instructions,
155                summary: this._convertSummary(summary),
156                inputWaypoints: inputWaypoints,
157                actualWaypoints: mappedWaypoints.waypoints
158                //waypointIndices: mappedWaypoints.waypointIndices
159            }];
160	    console.log(alts);
161            callback.call(context, null, alts);
162        },
163
164        _decodePolyline: function(geometry) {
165            var coords = geometry,
166                latlngs = new Array(coords.length),
167                i;
168
169            for (i = 0; i < coords.length; i++) {
170                latlngs[i] = new L.LatLng(coords[i].latitude, coords[i].longitude);
171            }
172
173            return latlngs;
174        },
175
176        _toWaypoints: function(inputWaypoints, vias) {
177            var wps = [],
178                i;
179            for (i = 0; i < vias.length; i++) {
180                wps.push({
181                    latLng: L.latLng(vias[i]),
182                    name: inputWaypoints[i].name,
183                    options: inputWaypoints[i].options
184                });
185            }
186
187            return wps;
188        },
189
190        buildRouteUrl: function(waypoints, options) {
191            var locs = [],
192                i,
193                url = "",
194                _options = {
195                            routeType: this.options.routeType,
196                            language: this.options.language,
197                            instructionsType: this.options.instructionsType,
198                            traffic: this.options.traffic,
199                            avoid: this.options.avoid,
200                            travelMode: this.options.travelMode,
201                            vehicleMaxSpeed: this.options.vehicleMaxSpeed,
202                            vehicleWeight: this.options.vehicleWeight,
203                            vehicleAxleWeight: this.options.vehicleAxleWeight,
204                            vehicleLength: this.options.vehicleLength,
205                            vehicleWidth: this.options.vehicleWidth,
206                            vehicleHeight: this.options.vehicleHeight,
207                            departAt: this.options.departAt,
208                            arriveAt: this.options.arriveAt,
209                            vehicleCommercial: this.options.vehicleCommercial
210                    };
211
212            if (_options.avoid == "" || _options.avoid == [])
213                delete _options.avoid;
214
215            if (_options.instructionsType == "")
216                delete _options.instructionsType;
217
218            if (_options.language == "")
219                delete _options.language;
220
221            if (_options.departAt.match(/^(\d{4})\-(\d{2})\-(\d{2})T(\d{2}):(\d{2}):(\d{2})$/) === null)
222                delete _options.departAt;
223
224            if (_options.arriveAt.match(/^(\d{4})\-(\d{2})\-(\d{2})T(\d{2}):(\d{2}):(\d{2})$/) === null)
225                delete _options.arriveAt;
226
227            for (i = 0; i < waypoints.length; i++)
228                locs.push(waypoints[i].latLng.lat + ',' + waypoints[i].latLng.lng);
229
230            return this.options.serviceUrl + '/' + locs.join(':') + '/json?key=' +
231                    this._apiKey + '&' + Object.keys(_options).map(function(k) {
232                        return encodeURIComponent(k) + '=' + encodeURIComponent(_options[k])
233                    }).join('&');
234        },
235
236        _convertInstructions: function(summaries) {
237            var result = [],
238                i;
239
240            // tomtom don't provide any instructions, but we will create instructions from summary
241            for (i = 0; i < summaries.length; i++) {
242                result.push({ distance: summaries[i].summary.lengthInMeters,
243                              time: summaries[i].summary.travelTimeInSeconds,
244                              type: (i == summaries.length - 1 ? "DestinationReached" : "WaypointReached"),
245                              index: summaries[i].index });
246            }
247
248            return result;
249        },
250
251        _convertSummary: function(summaries) {
252            var result = { totalDistance: 0,
253                           totalTime: 0 },
254                i;
255
256            for (i = 0; i < summaries.length; i++) {
257                result.totalDistance += summaries[i].summary.lengthInMeters;
258                result.totalTime += summaries[i].summary.travelTimeInSeconds;
259            }
260
261            return result;
262        },
263
264         _mapWaypointIndices: function(waypoints, instructions, coordinates) {
265            var wps = [],
266                wpIndices = [],
267                i,
268                idx;
269
270            wpIndices.push(0);
271            wps.push({ latLng: coordinates[0], name: waypoints[0].name });
272
273            for (i = 0; i < instructions.length; i++) {
274                if (instructions[i].type === "WaypointReached") {
275                    idx = instructions[i].index;
276                    wpIndices.push(idx);
277                    wps.push({
278                        latLng: coordinates[idx],
279                        name: waypoints[wps.length + 1].name
280                    });
281                }
282            }
283
284            wpIndices.push(coordinates.length - 1);
285            wps.push({
286                latLng: coordinates[coordinates.length - 1],
287                name: waypoints[waypoints.length - 1].name
288            });
289
290            return {
291                waypointIndices: wpIndices,
292                waypoints: wps
293            };
294        }
295    }); 
296
297    L.Routing.tomTom = function(apiKey, options) {
298        return new L.Routing.TomTom(apiKey, options);
299    };
300    
301})();

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.