javascript - 使用 D3.js 和 GeoJson 在 map 上的州显示一些文本

标签 javascript d3.js geojson

我一直在使用 Storm 和 Redis,只是为了可视化从 Redis 获取的数据,我需要渲染 map (印度)并根据状态放置数据。我已经正确渲染了 map ,但只是不知道如何在各自的州边界内显示文本。 任何帮助将不胜感激。谢谢。

<!DOCTYPE html>
<html lang="en">
<head>
<title>Visualization Demo</title>
<script type="text/javascript" src="d3.min.js"></script>
<script type="text/javascript" src="d3.geo.min.js"></script>

<link type="text/css" rel="stylesheet" href="color-scheme.css"/>
<style type="text/css">
svg {
    background: #282828;
}
body {
    background: #282828;
}
h1 {
    color:#999999;
}
#india {
    fill: #99FFCC;
    opacity: .9;
    stroke: white;
    stroke-width: 1.0;
}
#chart {
    margin-left:150px;
}
</style>
</head>

<body>
    <h1><center>VISUALIZATION</center></h1>
    <div id="chart"></div>
    <script type="text/javascript">
        var w = 1000;
        var h = 1500;
        var proj = d3.geo.mercator();
        var path = d3.geo.path().projection(proj);
        var t = proj.translate(); // the projection's default translation
        var s = proj.scale() // the projection's default scale
        var map = d3.select("#chart").append("svg:svg")
        .attr("width", w)
        .attr("height", h)
        .call(initialize);
        var india = map.append("svg:g")
        .attr("id", "india");
        d3.json("india-states.json", function (json) {
            india.selectAll("path")
            .data(json.features)
            .enter().append("path")
            .attr("d", path);
        });
        function initialize() {
            proj.scale(9000);
            proj.translate([-1520, 1000]);
        }
    </script>
</body>
</html>

最佳答案

在您的 d3.json 函数中尝试一下:

india.selectAll("text")
    .data(json.features)
    .enter()
    .append("text")
    .attr("fill", "black")
    .attr("transform", function(d) { 
        var centroid = path.centroid(d);
        return "translate(" + centroid[0] + "," + centroid[1] + ")"
    })
    .attr("text-anchor", "middle")
    .attr("dy", ".35em")
    .text(function(d) {
          return d.properties.STATE_NAME;
    });

您可能没有 properties.STATE_NAME 作为州名,但只需在 JSON 中检查您应在此处使用的内容即可。

关于javascript - 使用 D3.js 和 GeoJson 在 map 上的州显示一些文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37115601/

相关文章:

javascript - 如何使用 d3.js 创建水平图例

node.js - 如何简化和消除 GeoJSON 多边形中的重叠

d3.js - D3js 从 GeoJSON 生成路径

javascript - 如何使用箭头键在不同表格之间导航文本框?

javascript - 如何在 Vue 中的方法函数之前设置变量(去抖)?

javascript - 处理时间数据,如何将此 AS3 行转换为 Javascript?

javascript - 检测浏览器是否已将选择转换为微调器?

d3.js - dc.js 使用 crossfilter 将回归图合并到现有的散点图中

javascript - 使用 D3 网格问题和控制台错误的分组条形图

javascript - 将 geojson 层添加到 openlayers 3