2017-04-05 100 views
2

我已經創建了一個包含地圖中所有州和縣的地圖。在地圖中,我有一些與盆地有關的縣。我允許用戶在地圖上添加新的盆地,但在用戶保存新盆地後,它不會顯示在圖例中。重繪圖例之前,我重繪了地圖功能並清除了圖例。但是,直到完全刷新頁面之後,新信息纔會顯示出來。如何使用javascript保存的新數據刷新d3地圖

這是我第一次畫地圖:

 function drawMap() { 
      //DRAW MAP 
      d3.json("js/map.json", function(error, mapData){ 
       if (error) throw error; 

       //draw counties 
       map.svg.append("g") 
        .selectAll("path") 
        .data(topojson.feature(mapData, mapData.objects.counties).features) 
        .enter().append("path"); 

       //draw county-borders 
       map.svg.append("path") 
        .datum(topojson.mesh(mapData, mapData.objects.counties, function(a, b) { return a!==b; })) 
        .attr("class", "countylines borders") 
        .attr("d", map.path); 
       //draw state-borders 
       map.svg.append("path") 
        .datum(topojson.mesh(mapData, mapData.objects.states, function(a, b) { return true; })) 
        .attr("class", "states borders") 
        .attr("d", map.path); 
       } 
     } 

而且這裏是我畫的傳說:

  function drawMapLegend() { 
       $("#mapLegend").empty(); 
       $("#paddLegend").empty(); 
       $("#subLegend").empty(); 
       // Create map legend svg layer for Basins 
       var basinLen = basin.length; 
       map.legendBasin = d3.select("#mapLegendDiv").append("div") 
        .attr("id", "mapLegend") 
        .append("svg") 
        .attr("height", 750) 
        .attr("style", "width:100%;") 
        .append("g"); 
       //display basin names in the legend 
       for(i=0;i<basin.length;i++) { 
        map.legendBasin.append("text") 
         .attr("x", 15).attr("y", (i*16)+20) 
         .attr("class", "basinText") 
         .text(basin["BasinName"][i]); 
       } 
      } 

保存我更新爲新盆陣列陣列狀物體後。我知道,這工作BC我console.log保存之前和之後的響應,它顯示了新盆地。我怎樣才能讓地圖刷新以顯示圖例中的新盆地?保存後,我調用drawMapLegend();

回答

1

您應該使用D3的數據綁定方法。 Mike Bostock有greatdocs解釋它是如何工作的。第一個有些過時,但仍然清楚地解釋事情。

綁定盆地陣列的「map.legendBasin」選項,然後在更新盆地數組,你可以只用輸入()選擇要追加新要素。

你會做類似如下:

map.legendBasin 
    .data(basin, function(d){return d;})//join using key 
    .enter() 
    .append("text") 
    .attr("x", 15)....//etc whatever stuff you want 

注意到,此代碼是可重複使用的兩個第一次,當新的元素進來當新的陣列來可以再次調用此函數和。只有新元素將獲得創建爲重點,將匹配現有的元素,同時也不會爲新的元素因此進入()選擇將只包含尚未附加作爲DOM元素的數據。您可以使用exit()選項以防需要刪除元素。