2014-01-25 34 views
0

我是d3.js的新手,但我可以繪製topojson文件,居中並計算比例(顯然使用幾個問題和stackoverflow的答案)。現在,我想要更改顯示的topojson,我的意思是,刪除實際並加載一個新的並顯示它。D3.js:繪製一個新的topojson並刪除舊的

我可以加載新的,但不顯示。你能幫我解決錯誤嗎?

<!DOCTYPE html> 
<meta charset="utf-8"> 
<style> 


rect { 
    fill: none; 
    pointer-events: all; 
} 

    .feature { 
     fill: #ccc; 
     cursor: pointer; 
    } 

    .feature.active { 
     fill: orange; 
    } 

    .mesh { 
     fill: none; 
     stroke: #fff; 
     stroke-width: .5px; 
     stroke-linejoin: round; 
    } 
</style> 
<body> 
<script src="http://d3js.org/d3.v3.min.js"></script> 
<script src="http://d3js.org/topojson.v1.min.js"></script> 
<script> 

var x = d3.scale.linear() 
    .domain([0, width]) 
    .range([0, width]); 

var y = d3.scale.linear() 
    .domain([0, height]) 
    .range([height, 0]); 

var width = 960, 
    height = 500, 
    active; 


var svg = d3.select("body") 
    .append("svg") 
    .attr("width", width) 
    .attr("height", height) 
    .on("click", reset); 

var g = svg.append("g"); 



var projection = d3.geo.albers() 
    .scale(1) 
    .translate([0,0]); 

var path = d3.geo.path() 
    .projection(projection); 

createMap("aguascalientes.topojson"); 

function createMap(topojsonFile) { 
    d3.json(topojsonFile, function(error, tj) { 

     console.log(tj); 

     for(key in tj.objects) { features = tj.objects[key]; } 

     var estados = topojson.feature(tj, features); 

     var b = path.bounds(estados); 
     var s = 0.95/ Math.max((b[1][0] - b[0][0])/width, (b[1][1] - b[0][1])/height); 
     var t = [(width - s * (b[1][0] + b[0][0]))/2, (height - s * (b[1][1] + b[0][1]))/2]; 

     projection 
      .scale(s) 
      .translate(t); 

     g.selectAll("path") 
      .data(topojson.feature(tj, features).features) 
      .enter().append("path") 
      .attr("d", path) 
      .attr("class", "feature") 
      .on("click", click); 

     g.append("path") 
      .datum(topojson.mesh(tj, features, function(a,b) { return a !== b; })) 
      .attr("class", "mesh") 
      .attr("d", path); 
    }); 
} 


function updateData() { 
    console.log("Update"); 
    svg = d3.select("body").transition(); 
    createMap("estados.topojson"); 
} 
</script> 


<body> 
    <div id="option"> 
    <input name="updateButton" 
      type="button" 
      value="Update" 
      onclick="updateData()" 
    /> 
    </div> 
</body> 

在此先感謝

回答

3

你實際上並沒有刪除舊的,只有在.enter()選擇操作,因此沒有任何反應。要刪除添加新路徑之前,那裏的東西,做

svg.selectAll("path").remove(); 

,只是行

d3.json(topojsonFile, function(error, tj) { 
+0

優良的售後服務,即加載數據後!我只是做了你告訴我的一切都好! (我也刪除了代碼'svg = d3.select(「body」)。transition();'並將'var path = ...'和'var projection = ...'移到'createMap )') – nanounanue