在使用d3.js制作的地图上显示图标/图像,而不是圆圈/路径

Display icons/image instead of circle/path on map made with d3.js

本文关键字:图像 图标 路径 显示图 显示 js d3 地图      更新时间:2023-09-26

我可以使用d3.js成功地在openlayers底图上显示一些点,但是我想实际显示图标(目前使用png图标)而不是svg点。

是否可以加载png/jpg/svg图像到地图使用d3.js?

到目前为止,我可以将图标直接加载到svg上,但所有标记都位于同一位置,所以我认为我在正确转换坐标时遇到了问题。

    var feature = svg.selectAll("path")
          .data(amenities.features)
          .enter()
          .append("svg:image")
          .attr("xlink:href", "maki/renders/post-18@2x.png")
          .attr("x", function(d, i) {return amenities.features[i].geometry.coordinates[0]})
          .attr("y", function(d, i) {return amenities.features[i].geometry.coordinates[1]})
          .attr("width", "20")
          .attr("height", "20")
          .attr("class", "amenity");

以前,我已经能够使用"模式"创建一个带有图像背景的svg来显示图像,所以这也是一种可能性,但我无法翻译代码以使用d3的地理方面。

我知道我正在写的图标,目前的'svg'div,所以他们不能正确地转换,当我放大和缩小。我的目标是将图像写入'g'div,如在代码中:

    var feature = g.selectAll("path")

但是当我使用这一行时,元素出现在文档上,但是图标实际上没有呈现在地图上

这里有几个问题。首先,我不确定您是否完全掌握d3选择是如何工作的,正如您将amenities.features绑定到您的选择,然后通过索引访问xy属性所表明的那样。有关这方面的更多详细信息,请参阅选择如何工作。此外,您需要通过地理投影函数将特征的地理坐标转换为屏幕坐标。这应该使您接近:

// more projections: https://github.com/d3/d3-geo-projection/
var projection = d3.geoAlbers();
var amenities = svg.selectAll('.amenities')
     .data(amenities.features);
   amenities.enter().append('image');
    
   amenities
    .attr("class", "amenities")     
    .attr("xlink:href", "maki/renders/post-18@2x.png")
    // The data is already bound so use it instead of the index. Als, 
    // you need to translate geo coordinates to screen coordinates by 
    // passing them through your projection function.
    .attr("x", function(d,i) {return projection(d.geometry.coordinates)[0];})
    .attr("y", function(d,i) {return projection(d.geometry.coordinates)[1];})
    .attr("width", "20")
    .attr("height", "20")

我不认为我使用的组是合适的但我认为关键是有transform然后翻译的东西在那里。

我的例子是http://bl.ocks.org/mpmckenna8/b87df1c44243aa1575cb。

但是因为我没有正确地使用分组,我不知道图标是否会像你想要的那样处理缩放。在我的例子中,我只是将图像附加到我创建的圆圈中。

  .attr("transform", function(d) { return "translate(" + projection(d.geometry.coordinates) + ")"; })
  .attr('opacity',.3)
  .attr('fill', '#fad959')