[GIS] Leaflet Routing Machine calculate routes in loop

javascriptleaflet

I have an array with coordinates ([[54.73, 55.74], [55.66, 54.73]…]). I want to get route from each point to another. E.g. if I have 3 points a1, a2, a3, I want to calculate routes a1a2, a1a3, a2a1, a2a3 etc. I need this to make distance matrix later. Here is my loop where coords is array of coordinates

function routingLoop() {
            for (var i = 0; i < coords.length; i++){
                for (var j = 0; j < coords.length; j++){
                    var routing;
                    routing = L.routing.control({
                        waypoints:[
                            L.latLng(coords[i][0], coords[i][1]),
                            L.latLng(coords[j][0], coords[j][1]),
                        ],
                    }).addTo(Map);
                }
            }
        }

But I get this error Routing error:
Object { status: -3, message: "TypeError: this._altContainer is undefined" }
. Any ideas what's wrong with that code?

Best Answer

It might look dumb but that's how I did it after all. Hope someday someone will find it useful. Basically I just calculated routes using mapbox directions api (it's free and you can send up to 300 requests per/min) and used it's summary (btw it appears to me that the most comfortable way is to use LRM ONLY to draw nice looking routes and if you need some data about it, better use OSRM or another routing api)

function getRoutSummary(i, j) {
                var url = 'https://api.mapbox.com/directions/v5/mapbox/driving/' +
                        coords[i][1] + ',' + coords[i][0] + ';' +
                        coords[j][1] + ',' + coords[j][0] +
                        '?geometries=geojson&access_token=YOUR TOKEN HERE';

                var req = new XMLHttpRequest();    
                req.responseType = 'json';    
                req.open('GET', url, true);

                req.onload = function () {
                    var jsonResponse = req.response;
                    var distance = jsonResponse.routes[0].distance;
                    console.log('Distance between ' +
                        'coords[' + i  +'][1]' + ',' + 'coords[' + i + '][0]' + ' and ' +
                        'coords[' + j  +'][1]' + ',' + 'coords[' + j + '][0]' +
                        ' is ' + distance);                    
                };
                req.send();
        }

console.log only to make me comfortable. And then iterate through array of coordinates

function getAllRoutes(){
            console.log('Begin getAllRoutes');
            for (var i = 0; i < coords.length; i++){
                for (var j = 0; j < coords.length; j++){
                    getRoutSummary(i, j);
                }
            }
        }