【问题标题】:Plot points in map d3 javascript在地图 d3 javascript 中绘制点
【发布时间】:2018-05-29 00:20:01
【问题描述】:

我想在我使用图像的地图上绘制名为 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 是南数,而 cy 是同一个数。我想也许我的数组还没有被读取。但我不确定这些问题。我被卡住了。你们能解决我的问题吗?谢谢

【问题讨论】:

  • 可能删除子集[0][1]
  • @RyanMorton 感谢您的回答。协调器 cx 和 cy 与现在图中的数字不同,但它们与其他线路的数字仍然相同,并且地图上仍然没有点
  • 忽略前面的评论。数据是什么样的?您将 lat 或 long 发送到投影函数似乎很奇怪。两个坐标不应该一起去投影以正确评估 cx 和 cy 吗?

标签: javascript csv d3.js plot


【解决方案1】:

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

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>

【讨论】: