用D3在地图上绘制点

时间:2020-11-28 20:31:06

I'm trying to plot a few points onto a map using the D3 geo library based on latitudes and longitudes. However, when I pass these values into my projection function, it results in coordinates that our outside the bounds of my SVG image. My code is based on this example provided in the documentation.

我正在尝试用基于纬度和经度的D3地理库在地图上绘制一些点。但是,当我将这些值传递到投影函数时,会产生坐标,这超出了SVG图像的界限。我的代码基于文档中提供的这个示例。

I've thrown the current code up at: http://bl.ocks.org/rpowelll/8312317

我已经在http://bl.ocks.org/rpowelll/8312317上抛出了当前的代码

My source data is a simple array of objects formatted like so

我的源数据是一组简单的格式化对象。

var places = [
  {
    name: "Wollongong, Australia",
    location: {
      latitude: -34.42507,
      longitude: 150.89315
    }
  },
  {
    name: "Newcastle, Australia",
    location: {
      latitude: -32.92669,
      longitude: 151.77892
    }
  }
]

Following this I set up an Plate Carrée projection like so:

在此之后,我建立了一个像这样的板式Carree投影:

var width = 960,
height = 480

var projection = d3.geo.equirectangular()
    .scale(153)
    .translate([width / 2, height / 2])
    .precision(.1);

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

From there I draw the map with code effectively identical to the linked example. At the end of my script, I use the following code to plot points on this map:

从那里,我用与链接示例完全相同的代码绘制地图。在我的脚本的最后,我使用下面的代码在这个地图上绘制点:

svg.selectAll(".pin")
    .data(places)
  .enter().append("circle", ".pin")
    .attr("r", 5)
    .attr("transform", function(d) {
      return "translate(" + projection([
        d.location.latitude,
        d.location.longitude
      ]) + ")"
    })

However this code results in points that are outside of the SVG element's bounds. Is there anything obvious I'm doing wrong here?

但是,这段代码会产生SVG元素边界之外的点。有什么明显的地方我做错了吗?

1 个解决方案

#1


15  

You have a simple typo in your code -- coordinates should be passed as (longitude, latitude) to the projection, not the other way round. This code should work fine:

您的代码中有一个简单的拼写错误——坐标应该作为(经度、纬度)传递到投影,而不是反过来。这段代码应该可以正常工作:

 svg.selectAll(".pin")
  .data(places)
  .enter().append("circle", ".pin")
  .attr("r", 5)
  .attr("transform", function(d) {
    return "translate(" + projection([
      d.location.longitude,
      d.location.latitude
    ]) + ")";
  });

#1


15  

You have a simple typo in your code -- coordinates should be passed as (longitude, latitude) to the projection, not the other way round. This code should work fine:

您的代码中有一个简单的拼写错误——坐标应该作为(经度、纬度)传递到投影,而不是反过来。这段代码应该可以正常工作:

 svg.selectAll(".pin")
  .data(places)
  .enter().append("circle", ".pin")
  .attr("r", 5)
  .attr("transform", function(d) {
    return "translate(" + projection([
      d.location.longitude,
      d.location.latitude
    ]) + ")";
  });