在d3地图投影周围创建弯曲的边框

时间:2019-02-24 21:16:01

标签: javascript d3.js maps

我已使用here显示的geoNaturalEarth1()在d3中创建了世界地图。我使用具有此投影的世界的geojson地图来获取地图,如下面的代码所示。但是,这表明这些国家无国界地漂浮在太空中。我想在地图投影周围绘制边框,以使其看起来更像地图。边框将是投影图像中所示的平坦的顶部/底部,弯曲的侧面。这可能吗,我该怎么做呢?

var projection = d3.geoNaturalEarth1()
    .translate([w/2, h/2])
    .scale(247)
    .center([0,0]);

var path = d3.geoPath().projection(projection);

d3.json('map.geojson').then(function(world) {

    svg.selectAll(".emissions_path")
        .data(world.features)
        .enter().append("path")
        .attr('fill', '#fff')
        .attr("d", path)
        .style('stroke', 'black')
        .style('stroke-width', '0.5px');

2 个答案:

答案 0 :(得分:2)

您可以向路径生成器提供Sphere类型的geojson:

  

还支持Sphere类型,这对于呈现   地球轮廓;球体没有坐标。 (docs

这看起来像:

var outline = {type:"Sphere"}

它可以直接传递给路径生成器:

var context = d3.select("canvas").node().getContext("2d"),
    projection = d3.geoNaturalEarth1()
      .scale(70)
      .translate([200,100])
    path = d3.geoPath()
      .context(context)
      .projection(projection);

d3.json("https://unpkg.com/world-atlas@1/world/110m.json", function(error, world) {
  if (error) throw error;

  context.beginPath();
  context.fillStyle = "lightgreen";
  path(topojson.feature(world, world.objects.land));
  context.fill();
  
  context.beginPath();
  context.strokeStyle = "#ccc";
  path({type: "Sphere"})
  context.stroke();
  
});
<canvas width="500" height="300"></canvas>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="https://unpkg.com/topojson-client@3"></script>


顺便说一句,还有d3.geoGraticule,它可以定期绘制子午线和平行线:

var context = d3.select("canvas").node().getContext("2d"),
        projection = d3.geoNaturalEarth1()
          .scale(70)
          .translate([200,100])
        path = d3.geoPath()
          .context(context)
          .projection(projection);

    d3.json("https://unpkg.com/world-atlas@1/world/110m.json", function(error, world) {
      if (error) throw error;

      context.beginPath();
      context.fillStyle = "lightgreen";
      path(topojson.feature(world, world.objects.land));
      context.fill();
  
      context.beginPath();
      context.strokeStyle = "#eee";
      path(d3.geoGraticule10())
      context.stroke();
      
      context.beginPath();
      context.strokeStyle = "#000";
      path({type:"Sphere"})
      context.stroke();        
      
    });
<canvas width="500" height="300"></canvas>
    <script src="https://d3js.org/d3.v4.min.js"></script>
    <script src="https://unpkg.com/topojson-client@3"></script>

答案 1 :(得分:0)

Andrew Reid的代码翻译成SVG而不是canvas代码如下

var projection = d3.geoNaturalEarth1()
  .translate([w / 2, h / 2])
  .scale(247);

var path = d3.geoPath().projection(projection);

svg.enter("path")
  .datum({type: "Sphere"})
  .attr("d", path)
  .style("fill", "none")
  .style("stroke", "black")
  .style("stroke-width", 3);