Search code examples
javascriptfor-loopnestedleafletpolyline

Optimise Coordinate Data Collection using array JavaScript


Currently I am storing distinct routes in routea, routeb, routec, etc. I would like to collect them all onto one route and a set of two nested for loops to generate polylines. Currently, I am using brute force, so ...

for (var i = 0, latlng1= [], len1 = routea.length; i < len1; i++) {
        latlng1.push(new L.LatLng(routea[i][0], routea[i][1]));
    }

    for (var i = 0, latlng2 = [], len2 = routeb.length; i < len2; i++) {
        latlng2.push(new L.LatLng(routeb[i][0], routeb[i][1]));}

My attempt to nest the loop has been

route = [routea, routeb, routec];
for (var j = 0, lena = route; j < lena; j++) {
    for (var i = 0, latlng1= [], len = route[j].length; i < len; i++) {
        latlng.push(new L.LatLng(route[i][0], route[i][1]));
    }
    var pathmat = L.featureGroup ([L.polyline(latlng1[j])]);
    }

But I get the following error Uncaught TypeError: Cannot read property '_leaflet_id' of undefined at Object.stamp


Solution

  • No need to loop through the routea, routeb... tables. You can build a polyline just with a coordinates array :

    var route = [routea, routeb, routec];
    var polylines = [];
    for (var j = 0; j < route.length; j++) {
        polylines.push(L.polyline(route[j]);
    }
    

    Then do whatever you want with the polylines. If you want to put all of them in a feature group :

    var fg = L.featureGroup(polylines);