0
I have made a map in d3 for usa. Now I want to apply different color as soon as i move my mouse on the province area or from first have many colors to the map.

My code is :
 <script type="text/javascript">
      var w = 1560;
      var h = 900;
      var color = d3.scale.category10();
      var proj = d3.geo.mercator();
      var path = d3.geo.path().projection(proj);
      var t = proj.translate(); // the projection's default translation
      var s = proj.scale() // the projection's default scale

      var map = d3.select("#vis").append("svg:svg")
        .attr("width", w)
        .attr("height", h)
        .call(d3.behavior.zoom().on("zoom", redraw));

      var axes = map.append("svg:g").attr("id", "axes");

      var xAxis = axes.append("svg:line")
        .attr("x1", t[0])
        .attr("y1", 0)
        .attr("x2", t[0])
        .attr("y2", h);

      var yAxis = axes.append("svg:line")
        .attr("x1", 0)
        .attr("y1", t[1])
        .attr("x2", w)
        .attr("y2", t[1]);


      var uk = map.append("svg:g").attr("id", "uk");
 d3.json("tryusa.json", function (json) {
          uk.selectAll("path")
          .data(json.features).on("mouseover", function () { d3.select(this).style("fill", "aqua"); })
        .enter().append("svg:path")
         .attr("d", path)
          .on("click", click)
          .on("click", function () { window.open("Default3.aspx") })
        .append("svg:title")
        .text(function (d) { return d.properties.name; })

      });

      svg.selectAll(".subunit")
    .data(topojson.object(uk, uk.objects.subunits).geometries)
  .enter().append("path")
    .attr("class", function (d) { return "subunit " + d.id; })
    ;


      function redraw() {
          var tx = t[0] * d3.event.scale + d3.event.translate[0];
          var ty = t[1] * d3.event.scale + d3.event.translate[1];
          proj.translate([tx, ty]);

          // now we determine the projection's new scale, but there's a problem:
          // the map doesn't 'zoom onto the mouse point'
          proj.scale(s * d3.event.scale);

          // redraw the map
          uk.selectAll("path").attr("d", path);

          // redraw the x axis
          xAxis.attr("x1", tx).attr("x2", tx);

          // redraw the y axis
          yAxis.attr("y1", ty).attr("y2", ty);
      }



  </script>

我尝试了一些类似鼠标悬停事件的事情,但我无法得到结果。

我还尝试使用内置功能自动显示不同的颜色。但我也无法做到这一点。我是 d3 的新手,请您帮帮我。颜色可以放在鼠标悬停事件上或从第一个开始。什么都行。

4

1 回答 1

0

您可以在用于填充的函数上使用一个参数(以及其他所有内容):

.data(json.features)
.on("mouseover", function (d, i) { d3.select(this).style("fill", d.color); })

json.features颜色是数组每个字段的属性之一。在这个函数中,参数d代表数据(这里是状态),i代表状态在json.features数组中的索引。

在这个 d3 示例中可以看到节点颜色的示例实现:http: //bl.ocks.org/mbostock/4062045

于 2013-03-20T07:15:29.427 回答