如何在D3.js中添加到地理位置的链接(创建为json路径)
How to add a link to a geography (created as a json path) in D3.js?
我在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形状的链接:
-
<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);
-
正如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();});
});
相关文章:
- 使用jQuery迭代数组以创建链接
- 如何在jQuery中以有效的方式创建链接
- 使用其他页面上表单的文本创建链接
- 传单:如何在弹出窗口中创建链接选择器
- 用JavaScript创建链接,并将其集成到createTextNode()中
- 如何为图像的某些部分创建链接
- 如何使用onClick处理程序在React组件中创建链接
- Chrome扩展,从正文中的关键词创建链接
- 根据用户从jQuery UI可选下拉框中选择的内容创建链接
- 在列表中创建链接
- 如何在javascript中创建链接
- 正在节点d3.js之间创建链接,当前返回Uncaught TypeError:无法读取属性'weight'
- 使用 reactjs 创建链接的覆盖
- 如何基于URL的一部分为表中已有的每个链接创建链接
- 基于 Html 表单中的值创建链接,并将其重定向到该链接
- 为字母表中的所有字母创建链接
- 在角度中,创建链接中没有 # 且不修改服务器的 spa
- 无法让javascript从XML列表正确创建链接
- 如何使用 JSON 创建链接,单击这些链接时会显示在单独的
- 如何创建链接/按钮,该链接/按钮将导航到jquery移动页面之外的页面