javascript 使用 D3 在地图上绘制点

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20987535/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 19:46:13  来源:igfitidea点击:

Plotting points on a map with D3

javascriptsvgd3.jsgeo

提问by rpowell

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:

在此之后,我设置了一个 Plate Carrée 投影,如下所示:

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 元素的边界。有什么明显的我做错了吗?

回答by Lars Kotthoff

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
    ]) + ")";
  });