0

I have a JSON with different points. Each point has a different fields, like lon1 , lat1, lon2, lat2.

For each point I draw a line from point 1 to point 2. By means of a for I perform this operation for each point and I draw different polylines in the map.

The problem is that when I activate or deactivate the layer, only the last drawn line is hidden, not all lines.

In the map you can see all the lines, but it seems that in the layer it overwrites and deletes the last line generated.

Code:

for (var i = 0; i < json_ARAPointsPRU_0.features.length; i++) {

  var Lon1 = json_ARAPointsPRU_0.features[i].properties['Lon(d.dd)'];
  var Lat1 = json_ARAPointsPRU_0.features[i].properties['Lat(d.dd)'];
  var Lon2 = json_ARAPointsPRU_0.features[i].properties['LON2'];
  var Lat2 = json_ARAPointsPRU_0.features[i].properties['LAT2'];

  // array of coordinates
  var mylatlngs = [
    [Lat1, Lon1],
    [Lat2, Lon2]
  ];
  // draw a polyline in the map
  var polilineas = L.polyline(mylatlngs, {
    color: 'blue'
  });
  polilineas.addTo(map);

  // add " polilineas" into other layer
  var Velocidad2D = new L.LayerGroup();
  Velocidad2D.addLayer(polilineas);
  // Velocidad2D.addLayer(cabezas);  Possibility to add arrow head
}


// Code to LAYER CONTROL

var gropedOverlayslehen = {
  "Vel 2D": Velocidad2D
}

var layerControl = L.control.layers(basemaps, gropedOverlayslehen);

layerControl.addTo(map);
lejlun
  • 4,140
  • 2
  • 15
  • 31
ag1
  • 1
  • Ah, a classical variable scope problem. Do read about closures. https://stackoverflow.com/questions/111102/how-do-javascript-closures-work – IvanSanchez Aug 05 '21 at 18:12

1 Answers1

0

You need to put var Velocidad2D = new L.LayerGroup(); to the outside of the loop, else you overwrite it everytime.

var Velocidad2D = new L.LayerGroup();
for (var i = 0; i < json_ARAPointsPRU_0.features.length; i++) {

  var Lon1 = json_ARAPointsPRU_0.features[i].properties['Lon(d.dd)'];
  var Lat1 = json_ARAPointsPRU_0.features[i].properties['Lat(d.dd)'];
  var Lon2 = json_ARAPointsPRU_0.features[i].properties['LON2'];
  var Lat2 = json_ARAPointsPRU_0.features[i].properties['LAT2'];

  // array of coordinates
  var mylatlngs = [
    [Lat1, Lon1],
    [Lat2, Lon2]
  ];
  // draw a polyline in the map
  var polilineas = L.polyline(mylatlngs, {
    color: 'blue'
  });
  polilineas.addTo(map);

  // add " polilineas" into other layer
  Velocidad2D.addLayer(polilineas);
  // Velocidad2D.addLayer(cabezas);  Possibility to add arrow head
}


// Code to LAYER CONTROL

var gropedOverlayslehen = {
  "Vel 2D": Velocidad2D
}

var layerControl = L.control.layers(basemaps, gropedOverlayslehen);

layerControl.addTo(map);
Falke Design
  • 10,635
  • 3
  • 15
  • 30