javascript - D3,绘制 map ,可能的数据格式

标签 javascript d3.js

我正在尝试创建一个 map 并使用 d3 绘制一些点,我找到了一些很好的例子来构建,但我相信我被困住了。我的猜测是,我没有根据数据结构正确处理绘图点。我需要一些帮助 - 这是我的第一次尝试。这是我到目前为止所拥有的:

 var m_width = document.getElementById("map").offsetWidth,
width = 938,
height = 500;

 var projection = d3.geo.mercator()
.scale(150)
.translate([width / 2, height / 1.5]);

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

 var svg = d3.select("#map").append("svg")
.attr("preserveAspectRatio", "xMidYMid")
.attr("viewBox", "0 0 " + width + " " + height)
.attr("width", m_width)
.attr("height", m_width * height / width);

 svg.append("rect")
.attr("class", "background")
.attr("width", width)
.attr("height", height)


var g = svg.append("g");

 d3.json("scripts/world-110m2.json", function(error, us) {
g.append("g")
.attr("id", "countries")
.selectAll("path")
.data(topojson.feature(us, us.objects.countries).features)
.enter()
.append("path")
.attr("id", function(d) { return d.id; })
.attr("d", path)

});

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

window.addEventListener('resize', function(event){
var w = document.getElementById("map").offsetWidth;
svg.attr("width", w);
svg.attr("height", w * height / width);
  });

“地点”数据的结构如下

 var places = {"count":"392","earthquakes":[{"src":"us","eqid":"2010sdbk","timedate":"2010-01-31 15:18:44","lat":"-18.7507","lon":"169.3940","magnitude":"5.1","depth":"231.50","region":"Vanuatu"}

所有地点都位于地点对象数组“earthquakes”内。 (特别是在其中的经度和纬度)。

世界地图显示得很好,我只是无法让这些情节点发挥作用。非常感谢任何帮助。感谢您的阅读!!

最佳答案

你几乎已经成功了,但这里有几个问题:

1.) 您传递给 .data 的数据应该是一个数组(添加圈子的位置)。

2.) 在您的 places 对象中,您的纬度/经度是字符串,需要转换为数字。

尝试:

var places = {
   "count": "392",
   "earthquakes": [{
     "src": "us",
     "eqid": "2010sdbk",
     "timedate": "2010-01-31 15:18:44",
     "lat": "-18.7507",
     "lon": "169.3940",
     "magnitude": "5.1",
     "depth": "231.50",
     "region": "Vanuatu"
   }]
 };

 svg.selectAll(".pin")
   .data(places.earthquakes) //<-- pass array
   .enter()
   .append("circle")
   .attr("class","pin")
   .attr("r", 5)
   .attr("transform", function(d) {
     return "translate(" + projection([
       +d.lon, //<-- coerce to number
       +d.lat
     ]) + ")";
   });

示例 here .

关于javascript - D3,绘制 map ,可能的数据格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28440490/

相关文章:

javascript - 客户端重新加载页面时如何修复服务器故障?

javascript - 解析 d =""时出错

javascript - 在 HTTP/2 上引用或托管 javascript

javascript - 真正在 promise 中抛出错误

javascript - 如何对将在 CSS transitionEnd 事件后执行的 JavaScript 进行单元测试

javascript - 自制 "Captcha"系统 - javascript 中的一个小故障,无法启用提交按钮

javascript - AngularJS 中的可缩放网络图

javascript - 删除d3 js中的项目

javascript - D3 图表无法更新 -- 选择的进入和退出属性均为空

javascript - 数据未通过 XMLHttpRequest 发送