在地图 d3 javascript 中绘制点

2023-12-06

我想在我使用图像的地图上基于名为 tree.csv 的 csv 文件中的经度和纬度在地图上绘制。 我的 csv 文件包含很多行,所以我只在这里放一些行

经度和纬度

37.7295482207565 122.392689419827

37.8030467266869 122.425063628702 ...... 这是我的代码

d3.csv("/trees.csv", function(data) {
    dataset=data.map(function(d) { return [+d["Longitude"],+d["Latitude"] ];});
    console.log(data)
    var width = 750,
    height = width;

    // Set up projection that map is using
    var projection = d3.geo.mercator()
     .center([-122.433701, 37.767683])

     .scale(225000)
     .translate([width / 2, height / 2]);

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


    var svgContainer=d3.select("body").append("svg")
    .attr("width",width)
    .attr("height",height);
    svgContainer.append("image")
     .attr("width", width)
     .attr("height", height)
     .attr("xlink:href", "/Ilu.svg");

    var trees=svgContainer.selectAll("circles")
    .data(data).enter()
    .append("circles")

    var treesAttributes=trees
    .attr("cx",function(d) { return projection(d["Longitude"])[0];})
    .attr("cy",function(d) { return projection(d["Latitude"])[1];})
    .attr("r","100px")
    .style("fill","red");

我可以看到我的地图,但我看不到地图上的任何点。当我检查网络时。我看到 cx 是 Nan 数,cy 是相同的数。我想也许我的数组还没有被读取。但我不确定这些问题。我已经被困住了。你们能帮我解决这个问题吗?谢谢

enter image description here


您的问题在于您没有提供要投影的坐标。

d3 geoProjection 采用经度纬度对并将其投影到 x,y svg 坐标(投影返回的坐标为:[x,y],这就是您在代码中使用此形式的原因:projection(coord)[0]获取 cx 值)。您正在寻求仅投影经度,然后仅投影纬度:

.attr("cx",function(d) { return projection(d["Longitude"])[0];})
.attr("cy",function(d) { return projection(d["Latitude"])[1];})

在这种情况下,projection不会返回 svg 坐标,因为您没有为项目提供地理坐标。您需要投影经度和纬度,因为投影中生成的 x 和 y 值通常(并非总是)相互依赖 - 例如,在任何圆锥投影中,输出 y(或 x)值都依赖于纬度和经度。此外,由于projection()返回[x,y],因此每个投影都需要经度和纬度。

相反尝试:

.attr("cx",function(d) { return projection([d["Longitude"],d["Latitude"]])[0];})
.attr("cy",function(d) { return projection([d["Longitude"],d["Latitude"]])[1];})

请记住,d3 地理投影需要以下形式:projection([longitude, latitude]),改变经度和纬度的顺序会产生意想不到的结果。

var data = [
{longitude:1,latitude:1},
{longitude:-1,latitude:1},
{longitude:1,latitude:-1},
{longitude:-1,latitude:-1}
]

var svg = d3.select("body")
   .append("svg")
   .attr("width",200)
   .attr("height",200);
   
var projection = d3.geoMercator()
  .translate([100,100]);
  
var circles = svg.selectAll("circle")
  .data(data)
  .enter()
  .append("circle")
  .attr("cx",function(d) { return projection([d.longitude,d.latitude])[0];
   })
  .attr("cy",function(d) { return projection([d["longitude"],d["latitude"]])[1];
   })
   .attr("r",2)
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.10.0/d3.min.js"></script>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在地图 d3 javascript 中绘制点 的相关文章

随机推荐