如何在D3.js中添加到地理位置的链接(创建为json路径)

How to add a link to a geography (created as a json path) in D3.js?

本文关键字:创建 链接 json 路径 地理位置 D3 js 添加      更新时间:2023-09-26

我在d3.js中有一张纽约市行政区的简单地图。我想添加每个行政区的链接,但我不知道如何做到。

下面是我现在拥有的代码——只有一个到《纽约时报》网站的占位符链接。但是,它在<path>标记中添加了<a href>,这是不起作用的。如何附加链接?这可能吗?

谢谢!

<!DOCTYPE html>
    <meta charset="utf-8">
    <style>
    #boroughs {
      stroke: none;
        stroke-width: 0px;
        fill: #ddd;
        opacity:.7;
        position:absolute;
        top:0;
        left:0;
    }
    </style>
    <script src="http://d3js.org/d3.v3.min.js"></script>
    <body>
    <script>
    // map
    var width = Math.max(960, window.innerWidth),
        height = Math.max(500, window.innerHeight);
    var container = d3.select("body").append("div")
            .attr("id", "container")
            .style("width", width + "px")
            .style("height", height + "px");
    var projection = d3.geo.mercator()
            .center([-73.94, 40.70])
            .scale(80000)
            .translate([(width) / 2, (height)/2]);
    var path = d3.geo.path()
            .projection(projection);
    d3.json("nyc.json", function(error, nyb) {
    var map = container.append("svg")
            .attr("id", "boroughs")
            .style("width", width + "px")
            .style("height", height + "px")
            .selectAll("path")
            .data(nyb.features)
            .enter().append("path")
            .attr("class", function(d){ return d.properties.borough; })
            .attr("d", path)
            .attr("xlink:href", "http://www.nytimes.com");
    });

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

基本上有两种方法可以添加到SVG形状的链接:

  1. <svg:a>元素的使用。正如您在问题中已经说过的,如果它嵌套在应该添加链接的元素中,那么这将不起作用。就像HTML中的同名元素一样,您需要将<a>包装在应该附加链接的内容周围。

    var map = container.append("svg")
            .attr("id", "boroughs")
            .style("width", width + "px")
            .style("height", height + "px")
          .selectAll("path")
            .data(nyb.features)
            .enter()
            .append("a")                                     // The link goes here...
              .attr("xlink:href", "http://www.nytimes.com")                                     
            .append("path")                                  // ...wrapping the path.
              .attr("class", function(d){
                return d.properties.borough;
              })
              .attr("d", path);
    
  2. 正如Cyril的回答中所述,您可以附加一个处理click事件的JavaScript事件侦听器。

您可以在路径上附加一个点击侦听器,并打开如下窗口var win = window.open(YOUR_URL, "_blank"):

var map = container.append("svg")
        .attr("id", "boroughs")
        .style("width", width + "px")
        .style("height", height + "px")
        .selectAll("path")
        .data(nyb.features)
        .enter().append("path")
        .attr("class", function(d){ return d.properties.borough; })
        .attr("d", path)
        .on("click", function(d){var win = window.open(YOUR_URL, "_blank"); win.focus();});
});