我使用d3渲染了一张地图India.json。我想创建一个按钮,在点击时将呈现不同的地图India_simple.json。不幸的是,点击按钮似乎不起作用。代码如下 -
<!DOCTYPE html>
<meta charset="utf-8">
<!-- Set a style for our worldshape-data -->
<style>
path {
stroke: red;
stroke-width: 0.5px;
fill: grey;
}
</style>
<body>
<div id="option">
<input name="updateButton"
type="button"
value="Update"
onclick="updateData()" />
</div>
<!-- implementation of the hosted D3- and TopoJson js-libraries -->
<script src="http://d3js.org/d3.v3.min.js"></script>
<script src="http://d3js.org/topojson.v0.min.js"></script>
<!-- map creation -->
<script>
// canvas resolution
var width = 1000,
height = 600;
// projection-settings for mercator
var projection = d3.geo.mercator()
// where to center the map in degrees
.center([100, 30 ])
// zoomlevel
.scale(700)
// map-rotation
.rotate([0,0]);
// defines "svg" as data type and "make canvas" command
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
// defines "path" as return of geographic features
var path = d3.geo.path()
.projection(projection);
// group the svg layers
var g = svg.append("g");
// load data and display the map on the canvas with country geometries
d3.json("india.json", function(topology) {
g.selectAll("path")
.data(topojson.object(topology, topology.objects.collection)
.geometries)
.enter()
.append("path")
.attr("d", path)
});
function updateData() {
d3.json("india_simple.json", function(topology) {
g.selectAll("path")
.data(topojson.object(topology, topology.objects.collection)
.geometries)
.enter()
.append("path")
.attr("d", path);
});
}
</script>
</body>
</html>
控制台中没有错误。仅显示第一个地图,单击按钮时没有任何反应。我在dropbox中共享了两个json文件 - https://www.dropbox.com/sh/wrxyngyq4jdie9c/AACG2-dTzC79rRvlxlOC5poBa?dl=0
还尝试删除现有的svg,并用新的svg替换它。但是这段代码只附加了新的svgs,没有替代。 updateData代码 -
function updateData() {
d3.selectAll("svg > *").remove();
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
// defines "path" as return of geographic features
var path = d3.geo.path()
.projection(projection);
// group the svg layers
var g = svg.append("g");
d3.json("json.india_simple", function(topology) {
g.selectAll("path")
.data(topojson.object(topology, topology.objects.collection)
.geometries)
.enter()
.append("path")
.attr("d", path);
});