2017-04-05 1 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]); 
       } 
      } 

을 . 나는 그 작품이 저의 console.log에 저장 전후의 반응을 알고 있으며, 새로운 분지를 보여줍니다. 전설에 새 분지를 보여주기 위해지도를 새로 고침하려면 어떻게해야합니까? 저장 후 drawMapLegend();를 호출합니다.

답변

1

D3의 데이터 바인딩 방식을 사용해야합니다. Mike Bostock은 어떻게 작동하는지 설명하는 greatdocs을 가지고 있습니다. 처음에는 다소 구식이지만 여전히 명확하게 설명합니다.

basin 배열을 "map.legendBasin"선택 항목에 바인딩 한 다음 basin 배열을 업데이트 할 때 enter() 선택을 사용하여 새 요소를 추가 할 수 있습니다.

다음과 같이 할 것 :.이 코드는 처음으로 새로운 요소가 들어올 때 새로운 배열이되면 당신은 단순히 다시이 함수를 호출 할 수 있습니다 모두 재사용 가능한 것을

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

공지 사항 기존 엘리먼트에 대해 키가 일치 할 때 새로운 엘리먼트 만 생성 될 것이고 새로운 엘리먼트에 대해서는 키가 일치하지 않을 것이므로 enter() 선택은 이미 DOM에 엘리먼트로 추가되지 않은 데이터만을 포함 할 것이다. 요소를 제거해야하는 경우 exit()를 사용할 수 있습니다.

관련 문제