【问题标题】:d3js map, clipping geographic paths with bounding box?d3js 地图,用边界框裁剪地理路径?
【发布时间】:2022-06-23 15:55:40
【问题描述】:

我正在使用 d3js 构建地图。我可以轻松地从此geojson file 渲染美国州地图,并根据需要在其上绘制点数据(未显示)。但我想使用长/纬度值的边界框来剪辑可视化。

我什至不确定在什么阶段或在什么对象上进行剪裁,一般来说。在 d3 API 参考 (for instance here) 上有一些关于裁剪投影方法的简约文档。我不确定剪裁投影是否会有所帮助。

我的地图图像和我想要的地图输出 - 来自Wikle et al. 2019 - 已附上。我的 HTML 骨架很小,它调用了 js 脚本,并为 svg(“svg1”)提供了一个划分。

此消息末尾的代码生成此地图:

过滤掉阿拉斯加和夏威夷不是问题,也不属于这个问题。我想要一个像下面这样的图像(请忽略点数据,我只是对将状态路径剪裁到大小感到好奇):

这是我的js代码:

window.addEventListener("load", main)

function main(){
  // base svg and svg props
  const width = 400, height = 400;
  let facetWidth = width; 
  let facetHeight = height; 
  let svg1 = d3.select("#plot").append('svg')
    .style("width", width)
    .style("height", height)
    .attr("id", "svg1");

  // projection and generator
  let projection = d3.geoAlbersUsa();
  let geoGenerator = d3.geoPath().projection(projection);

  // state drawing function:
  function renderStates(data) {

    projection.fitSize([facetWidth, facetHeight], data); 

    svg1.append('g')
    .attr('id','statePaths')
    .attr('id','statePaths')
    .selectAll('path')
      .data(data.features)
      .join('path')
      .attr('d', geoGenerator)
      .attr('fill', '#ffffff')
      .attr('stroke', '#000')
    };

任何建议将不胜感激。我对使用 d3js 渲染地图还是很陌生。

【问题讨论】:

    标签: d3.js


    【解决方案1】:

    我将发布我自己问题的答案,以防它有用,因为在observables community 之外似乎没有很多使用 d3js 进行剪辑的明确示例。他们的示例对他们的平台有点专业(尽管它们很有帮助!)。

    为了将上述内容裁剪到感兴趣的区域,我使用了projection.postclip 函数,使用 d3.v7。我的代码现在太大,无法在此处包含,但以下是一般使用模式:

    // set the standard d3js projection stuff: 
    let projection = d3.geoEquirectangular()
      .translate([width/2, height/2])
      .scale(1000)
      .center([-89.04423584210527, 38.66203010526314])
       ;
    
    // get your geographic coordinates that you would like to use as a bounding box. 
    
    // In my case I am grabbing them from array called `stations` 
    // using d3 accessor functions: 
    
    let xMinLL = d3.min(stations, d => +d.lon);
    let yMinLL = d3.min(stations, d => +d.lat);
    let xMaxLL = d3.max(stations, d => +d.lon);
    let yMaxLL = d3.max(stations, d => +d.lat);
    
    
    // assign our pixel coordinates. Remember that y is flipped, up is down. 
    [xMinPix, yMaxPix] = projection([xMinLL, yMinLL]);
    [xMaxPix, yMinPix] = projection([xMaxLL, yMaxLL]);
    
    // update your projection with the pixel coordinates:
    const buff = 5;
    projection.postclip(d3.geoClipRectangle(xMinPix - buff,
                                            yMinPix - buff,
                                            xMaxPix + buff,
                                            yMaxPix + buff));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-05-11
      • 2017-12-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多