使用D3在地图上显示数据

时间:2019-01-10 12:39:42

标签: javascript d3.js topojson

我想使用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文件。

如您在图像中所见,地图工作正常: Map with D3 & TopoJson

所以我现在要做的是将数据添加到地图。数据如下所示:

[{
    "date": "1425168000000",
    "values": [{
        "name": "US",
        "value": 70421276
    }, {
        "name": "DE",
        "value": 5179869
    }, {
        "name": "GB",
        "value": 4515529
    }, {
        "name": "CN",
        "value": 2862945
    }]

因此,对于每个国家/地区,我都有与此数据不同的json文件。例如,我希望该数据在地图上带有黄色的点,值越大,我想要在地图上显示的点越多。

使用我拥有的数据和地图可能吗?如何开始呢?

1 个答案:

答案 0 :(得分:0)

首先获取大写字母位置列表(例如here),然后使用projection方法将经纬度坐标转换为SVG坐标(如{{3}中所示) }示例):

svg.selectAll("circle")
        .data(yourData).enter()
        .append("circle")
        .attr("cx", function (d) { return projection(latLon)[0]; })
        .attr("cy", function (d) { return projection(latLon)[1]; })
        .attr("r", function(d) { return d.size; })
        .attr("fill", "yellow");

假设您已将XLS文件转换为JSON数组(例如通过使用CSV文件),并且每个大写字母都具有latLon属性作为数组。并且d.size包含为SVG适当缩放的值。