0

我是新手d3.js,但我可以绘制一个topojson文件,居中并计算比例(显然使用stackoverflow的几个问题和答案)。现在,我想更改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>

提前致谢

4

1 回答 1

3

您实际上并没有删除旧的并仅对.enter()选择进行操作,因此没有任何反应。要在添加新路径之前删除那里的内容,请执行

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

加载数据后,即行后

d3.json(topojsonFile, function(error, tj) {
于 2014-01-25T09:40:14.657 回答