使用 D3 在地图上绘制点 [英] Plotting points on a map with D3

查看:50
本文介绍了使用 D3 在地图上绘制点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

我已将当前代码提交至:http://bl.ocks.org/rpowelll/8312317

I've thrown the current code up at: 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
    }
  }
]

在此之后,我像这样设置了一个 Plate Carrée 投影:

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

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

但是,此代码会导致点超出 SVG 元素的边界.有什么明显的我做错了吗?

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

推荐答案

您的代码中有一个简单的错字 -- 坐标应作为(经度、纬度)传递给投影,而不是相反.此代码应该可以正常工作:

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

这篇关于使用 D3 在地图上绘制点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆