【发布时间】:2019-01-10 12:39:41
【问题描述】:
我想使用 D3 在地图上显示数据。我有使用此代码的地图:
var jMap = $(".map"),
height = jMap.height(),
width = jMap.width(),
mapJsonUrl = 'https://ucarecdn.com/8e1027ea-dafd-4d6c-bf1e-698d305d4760/world110m2.json',
svg = d3.select(".map").append("svg")
.attr("width", width)
.attr("height", height);
var getProjection = function(worldJson) {
// create a first guess for the projection
var scale = 1,
offset = [ width / 2, height / 2 ],
projection = d3.geoEquirectangular().scale( scale ).rotate( [0,0] ).center([0,5]).translate( offset ),
bounds = mercatorBounds( projection ),
scaleExtent;
scale = width / (bounds[ 1 ][ 0 ] - bounds[ 0 ][ 0 ]);
scaleExtent = [ scale, 10 * scale ];
projection
.scale( scaleExtent[ 0 ] );
return projection;
},
mercatorBounds = function(projection) {
// find the top left and bottom right of current projection
var maxlat = 83,
yaw = projection.rotate()[ 0 ],
xymax = projection( [ -yaw + 180 - 1e-6, -maxlat ] ),
xymin = projection( [ -yaw - 180 + 1e-6, maxlat ] );
return [ xymin, xymax ];
};
d3.json(mapJsonUrl, function (error, worldJson) {
if (error) throw error;
var projection = getProjection(),
path = d3.geoPath().projection( projection );
svg.selectAll( 'path.land' )
.data( topojson.feature( worldJson, worldJson.objects.countries ).features )
.enter().append( 'path' )
.attr( 'class', 'land' )
.attr( 'd', path );
});
这是我的 javascript 文件。
<body>
<div class="map"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.2.2/d3.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/topojson/2.2.0/topojson.min.js"></script>
<script src="assets/js/index.js"></script>
</body>
这是我的 HTML 文件。
所以我现在要做的是向地图添加数据。这是数据的样子:
[{
"date": "1425168000000",
"values": [{
"name": "US",
"value": 70421276
}, {
"name": "DE",
"value": 5179869
}, {
"name": "GB",
"value": 4515529
}, {
"name": "CN",
"value": 2862945
}]
所以我有不同的 json 文件,其中包含每个国家/地区的这些数据。例如,我希望地图上的这些数据带有黄点,值越大,我想在地图上显示的点越多。
我拥有的数据和地图是否可行?我该如何开始?
【问题讨论】:
-
这可能是可能的,但我可以想象中国(10b+人口)的气泡会非常大,而蒙古(300万人口)的气泡,典型的方法是使用不同形状的颜色来表示数据而不是使用气泡。我在github 上有一个例子,希望它能给你一些关于如何实现它的想法。
标签: javascript d3.js topojson