【问题标题】:Displaying some text on States on Map using D3.js and GeoJson使用 D3.js 和 GeoJson 在地图上的状态显示一些文本
【发布时间】:2016-05-09 12:16:43
【问题描述】:

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

<!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>

【问题讨论】:

    标签: javascript d3.js geojson


    【解决方案1】:

    在你的 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 中检查您应该在此处使用的内容。

    【讨论】:

    • 那么它会在每个州边界内显示州名吗?
    • 并非如此:它将在给定点显示州名,由centroid x 和 y 设置。例如,如果您选择的字体大小太大,或者状态太小,则文本将通过边界。但是你可以根据状态调整字体大小,或者稍微改变位置,这很容易。顺便说一句,你找到同名的房产了吗?
    • 是的,它有效!谢谢朋友,你为我节省了很多时间。如果你能解释一下,我还需要对这段代码的工作原理进行一些解释
    • 是的,州名被指定为“id”
    • 不要使用“require”,这是一个强词! :-) 简而言之:对于每个路径(状态),都有一个名为centroid 的数组。这个数组有两个值,[0] 代表 x 位置,[1] 代表 y 位置。所以,我们只是附加了text并根据每个状态的centroid进行翻译。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-04
    • 1970-01-01
    • 2016-09-04
    • 2017-07-24
    • 2020-04-08
    • 1970-01-01
    相关资源
    最近更新 更多