datamaps绘制来自ajax响应的行

时间:2015-05-12 18:03:38

标签: jquery ajax d3.js

我正在尝试使用datamaps / d3来绘制来自ajax调用的行。

    var map = new Datamap({
                element: document.getElementById('container'),
                        scope: 'usa',

                });
 map.arc([
 {
  origin: {
      latitude: 40.229922,   // <-- I want these to be dynamic based on ajax
      longitude: -79.778889  // <-- I want these to be dynamic based on ajax
  },
  destination: {
      latitude: 38.818889,   // <-- I want these to be dynamic based on ajax
      longitude: -77.575    // <-- I want these to be dynamic based on ajax
  }
 },
{
  options: {
    strokeWidth: 14,
    strokeColor: 'rgba(100, 10, 200, 0.4)',
 greatArc: true 
  }
 },
],  {strokeWidth: 1, arcSharpness: 1.4});

如何使用ajax循环json响应来设置多个源/目的地?我会在代码的maps.arc部分放什么?

我的ajax回复:

{"1":{"origin":{"lat":"42.229922","lon":"-78.229922"},
      "destination":{"lat":"31.229922","lon":"-84.229922"}},
 "2":{"origin":{"lat":"47.229922","lon":"-69.229922"},
      "destination":{"lat":"44.229922","lon":"-74.229922"}}

1 个答案:

答案 0 :(得分:0)

首选解决方案是修改您的ajax响应以更好地符合所需的数据格式:

  • 使它成为一个对象数组,而不是对象的对象。
  • 纬度和经度属性应为数字而非字符串
  • lat和lon应该拼写

如果您不能或不会更改输出,那么效率较低的解决方案就是强制使用JavaScript:

// retrieve the json
d3.json('data.json', function(d) {
  var arcs = []; // array of parsed arcs
  for (var key in d) {
    var obj = d[key]; // get our inner object
    arcs.push({
      origin: {
        latitude: +obj.origin.lat, //convert to numbers
        longitude: +obj.origin.lon
      },
      destination: {
        latitude: +obj.destination.lat,
        longitude: +obj.destination.lon
      },
      options: {
        strokeWidth: 1,
        strokeColor: 'rgba(100, 10, 200, 0.4)',
        greatArc: true
      } // tack on options for each one
    });

    map.arc(arcs, {
      strokeWidth: 5,
      arcSharpness: 1.4
    }); // finally call .arc
  }
});

工作示例here

注意,你根本不需要jquery。