3

我是 d3 的新手,并试图弄清楚如何在将鼠标悬停在地图中的多边形上时显示一个属性(“NAME”)。我知道我应该按照以下方式做一些事情,.on("mouseover", function(d,i) { some function that returns properties.NAME }但不知道从那里去哪里。这是编写的 js,它只是将 NAME 属性静态放置在每个多边形上:

        <script>

        var width = 950,
        height = 650;

        var projection = d3.geo.albers()
        .scale(120000)
        .center([22.85, 40.038]);

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

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

        d3.json("newnabes.json", function(error, topology) {
                var nabes = topojson.object(topology, topology.objects.temp);

                svg.selectAll("path")
                .data(nabes.geometries)
                .enter().append("path")
                .attr("d", path);

                svg.selectAll(".subunit-label")
                .data(nabes.geometries)
                .enter().append("text")
                .attr("class", function(d) { return "subunit-label " + d.id; })
                .attr("transform", function(d) { return "translate(" + path.centroid(d) + ")"; })
                .attr("dy", ".35em")
                .text(function(d) { return d.properties.NAME; });
            });

        </script>

这是json的一小块

{"type":"Topology",
  "transform":{
  "scale":[0.00003242681758896625,0.000024882264664420337],
  "translate":[-75.28010087738252,39.889167081829875]},
  "objects":{
    "temp":{
      "type":"GeometryCollection",
      "geometries":[{
         "type":"Polygon",
         "id":1,
         "arcs":[[0,1,2,3,4,5,6]],
         "properties":{"NAME":"Haddington"}
       },{
         "type":"Polygon",
         "id":2,
         "arcs":[[7,8,9,10,-3,11]],
         "properties":{"NAME":"Carroll Park"}
       }...

谢谢

4

1 回答 1

4

So I figured it out, courtesy of: Show data on mouseover of circle

The simplest solution is to just append the names to the svg title attribute:

svg.selectAll("path")
 .data(nabes.geometries)
 .append("svg:title")
 .attr("class", function(d) { return "path " + d.id; })
 .attr("transform", function(d) { return "translate(" + path.centroid(d) + ")"; })
 .attr("dy", ".35em")
 .text(function(d) { return d.properties.NAME; });

Still investigating a more stylish solution to the problem (eg tipsy).

于 2013-01-27T21:18:45.340 回答