0

我目前正在尝试更新 TopoJson 地图的数据源,以便在按下按钮/调用 updateData() 函数时重新绘制地图上的点。

这是我的代码:

<head>

<script src="js/d3.js"></script>
<script src="http://d3js.org/topojson.v0.min.js"></script>

<style>
path {
  stroke: white;
  stroke-width: 0.25px;
  fill: grey;
}


</style>

    </head>

<body>


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

<script>
var width = 960,
    height = 500;

   var projection = d3.geo.mercator()

var div = d3.select("body").append("div")   
.attr("class", "tooltip")               
.style("opacity", 0);

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

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

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

// load and display the World
d3.json("data/world-110m2.json", function(error, topology) {

// load and display the cities
d3.json("data/commodities3.json", function(error, data) {
    g.selectAll("circle")
       .data(data)
       .enter()
       .append("circle")
       .attr("cx", function(d) {
               return projection([d.location_lon, d.location_lat])[0];})
       .attr("cy", function(d) {
               return projection([d.location_lon, d.location_lat])[1];})
       .style("fill", function(d){
    if(d.commodity_text == "Tin") {
    return "blue";
  } else {
    return "red";
  }


})
       .attr("r", function(d){
    if(d.commodity_text == "Iron") {
    return 10;
  } else {
    return 4;
  }


});
});




g.selectAll("path")
      .data(topojson.object(topology, topology.objects.countries)
          .geometries)
    .enter()
      .append("path")
      .attr("d", path)
});

// zoom and pan
var zoom = d3.behavior.zoom()
    .on("zoom",function() {
        g.attr("transform","translate("+ 
            d3.event.translate.join(",")+")scale("+d3.event.scale+")");
        g.selectAll("circle")
            .attr("d", path.projection(projection));
        g.selectAll("path")  
            .attr("d", path.projection(projection)); 

  });

svg.call(zoom)

function updateData(){

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

     d3.json("data/commodities3.json", function(error, data) {
    g.selectAll("circle")
       .data(data)
       .enter()
       .append("circle")
       .attr("cx", function(d) {
               return projection([d.location_lon, d.location_lat])[0];})
       .attr("cy", function(d) {
               return projection([d.location_lon, d.location_lat])[1];})
       .style("fill", function(d){
    if(d.commodity_text == "Tin") {
    return "blue";
  } else {
    return "red";
  }


})
       .attr("r", function(d){
    if(d.commodity_text == "Iron") {
    return 10;
  } else {
    return 4;
  }


});
});




}
    </script>
</body>
</html>

目前我正在我的变量“g”上调用我的转换函数,但我不确定从这里开始的地方。任何帮助将不胜感激。谢谢你。

4

0 回答 0