javascript - 如何在 D3.js 中添加地理链接(创建为 json 路径)?

标签 javascript d3.js

我在 d3.js 中有一张简单的纽约市行政区 map 。我想添加指向每个行政区的链接,但我不知道该怎么做。

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

谢谢!

<!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's answer 中所述你可以附加一个 JavaScript 事件监听器处理 click事件。

关于javascript - 如何在 D3.js 中添加地理链接(创建为 json 路径)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34716453/

相关文章:

javascript - d3 中的曲线

javascript - 脱糖等待..的

javascript - 使用 Chart.js 从世界银行 javascript JSON 下载中获取变化统计数据

javascript - JW Player 6 插件在 Firefox 中不工作 - Drupal

javascript - d3 时间格式 小时加 7 小时

javascript - D3JS : Interpolating missing time value as null in time series data

javascript - 为什么 console.log 不是 Shiny for R 中的函数?

javascript - HTML5 postMessage 返回未定义

javascript - 获取与当前日期最接近的日期 (javascript)

javascript - D3 饼图中的标签被 chop