0

So I have a map on which I draw trade routes(as arcs) between countries with arc.js. The arcs are different based on the year, and I basically want to be able to redraw the arcs based on what year I pick.

I create the arcs like so:

 //for every trade route, draw a arc from start to end 
var line_to_add;
for(var q = 0; q < dest_Coor.length; q++) {
    //create the arc
    var start = {x: from_Coor[0][0], y: from_Coor[0][1]};
    var end = {x: dest_Coor[q][0], y: dest_Coor[q][1]};
    var generator = new arc.GreatCircle(start,end);
    var line = generator.Arc(100, {offset: 10});

    //add it to map 
    line_to_add = L.geoJson(line.json(), {
        color: "#004c00"
    });

    //add the arc to global array of arcs
    allArrows.push(line_to_add);
    line_to_add.addTo(map);
}

When a different year is picked, I then try to delete the current arcs through this method, with allArrows being a global array of all arc objects(according to this question):

function deleteOldArcs() {
    for(var i = 0; i < allArrows.length; i++) {
        map.removeLayer(allArrows[u]);
    }
    //then reset the list of arrows:
    allArrows.length = 0;
}

However, this doesn't work and program execution just freezes inside map.removeLayer(allArrows[u]), and I don't understand why. I checked the list of map layers with map._layers, and the arc objects are in there... so why would calling map.removelayer not work?

Any help would be greatly appreciated, thanks!!

Community
  • 1
  • 1
ocean800
  • 3,489
  • 13
  • 41
  • 73

1 Answers1

1

You've got several options:

  1. Use Leaflet.Arc. It will create Leaflet layers directly, which might be easier to manage than the json blobs.

  2. Store line_to_add somewhere in an array, and call its remove() method later. From what I see, you want to reference allArrows[u], but you never fill up the allArrows data structure.

  3. Use a L.LayerGroup. Add the LayerGroup to the map, the arcs to the LayerGroup, then call its clearLayers() method.

IvanSanchez
  • 18,272
  • 3
  • 30
  • 45
  • Thanks for the answer! For 2, I think I am trying to do that right? I do `allArrows.push(line_to_add)` in the first code snippet I posted. So why wouldn't that work? As to 1, I would prefer not to have to change everything unless there is no other choice. As to 3, I don't want to really toggle between layers so it didn't seem like the best option, but I will look into it! – ocean800 May 18 '16 at 22:53
  • Hm, then I don't know why the code should hang up. Check the error console, set breakpoints, try to debug what happens when a layer is removed. Oh, and delete removed items from the array, so you don't try to remove already removed items. – IvanSanchez May 18 '16 at 22:59
  • Thanks for the answer! My error was something very stupid– I used `allArrows[u]` when my iterator is `i`. All the same, I changed things over to Leaflet.Arc, which I think will be nicer to use. – ocean800 May 19 '16 at 20:58