d3 - 向路径添加标记

Hay*_*ayo 5 javascript google-maps-api-3 d3.js

我正在尝试在 Google 地图叠加层上进行可视化,其中我用节点表示点,用边表示节点之间的链接。这些节点和边是使用 JavaScript 的 d3 库生成的。路径是根据 json 文件生成的。我现在想做的是在每条路径的末尾添加一个箭头标记,以指示路径的方向。为此,我使用了此示例,并首先指示 d3 在 defs 元素中添加包括其路径的标记,并且在生成路径期间,指示 d3 通过使用“marker-end”属性来包含标记使用 url 属性通过 id 引用标记元素的值。下面显示了在每个路径中定义和引用标记的代码片段。

d3.json("./json/routes.json", function(route_data) {

  var defs = layerPaths.append("defs")

  /* here I generate the marker shape and assign it the "arrow" id */
  defs.append("marker")
    .attr({
      "id": "arrow",
      "viewBox": "0 -5 10 10",
      "refX": 5,
      "refY": 0,
      "markerWidth": 4,
      "markerHeight": 4,
      "orient": "auto"
    })
    .append("path")
    .attr("d", "M 0 -5 L 10 0 L 0 5")
    .attr("class", "arrowHead");

  /* here I start generating the paths */ 
  var path = layerPaths.selectAll("path")
    .data(route_data)
    .each(setPathProperties)
    .enter()
    .append("path")
    .each(setPathProperties); // path properties are set by the setPathProperties function

  function setPathProperties(d) {

    /* I removed the complex functions that calculate path position as these are irrelevant for the question*/

    /* select the current path element and add attributes*/
    d3.select(this)
      .attr("class", "path")
      .attr("d", svgPen)
      .attr("stroke", "blue")
      .attr("stroke-width", 10)

    /* add the marker to the path by refering with a url statment to the marker element with the arrow id */
    .attr("marker-end", "url(#arrow)");
  }

})
Run Code Online (Sandbox Code Playgroud)

加载地图后,节点和路径会加载,但箭头不会出现。然而,marker-end 属性(包括其引用)位于每个路径元素中,而标记元素(包括其定义路径)位于 HTML 中。我认为“marker-end”属性的值“url(#arrow)”不起作用,尽管我不知道为什么。

有谁知道这里出了什么问题,为什么标记没有显示在地图上,以及如何解决这个问题?

Hay*_*ayo 2

好吧,我自己设法找到了问题的答案。我只是将defs元素附加到了错误的位置,它应该直接附加到 ,svg而我将它附加到 svg 中的一个组。