首页 > 解决方案 > d3.js 中的 API 数据可视化

问题描述

我是 d3.js 的新手。

我想在地图的每个城市部分绘制许多圆圈。

我试图从 API 获取数据并且它可以工作。

但是,它不会显示每个城市的圆圈而不会给我任何错误。

这是我的 script.js 代码:

     //Define path generator
  var path = d3.geo.path().projection(projection);

  //Group SVG elements together
  var features = svg.append("g");

 //Load TopoJSON data
    d3.json("Lebanon_Level2.json", function (error, syr) {

     if (error) return console.error(error);
    var subunits = topojson.feature(syr, syr.objects.gadm36_LBN_2);

      // Bind data and create one path per TopoJSON feature
      features.selectAll("path")
   .data(topojson.feature(syr, syr.objects.gadm36_LBN_2).features)
   .enter()
  .append("path")
  .attr("d", path)
  .attr("fill", "#e8d8c3")

    });

在 d3.js 中获取 API 数据

 d3.json('https://localhost/API/covidinfo/read.php',function(data) 
     {
      var location = data.records;
      console.log(location);
    
      features.selectAll('circle')
            .data(location)
            .enter()
            .append('circle')
            
            .attr('cx',function(d){
                location.map(d=>{
                    return projection([d.lng,d.lat])[0];
                })
            })
            .attr('cy',function(d){
                location.map(d=>{
                    return projection([d.lng,d.lat])[1];
                })
            })
            .attr("r", 15)
            .style("fill", "red")
            .style("opacity", 0.75);
            
  });


  

输出:圆圈出现在地图的左侧

API 数据 API数据输出

标签: javascriptapid3.jsdata-visualizationtopojson

解决方案


推荐阅读