javascript - D3 map 可见区域坐标

标签 javascript d3.js

这是我的 d3 可缩放 map 的简单代码:

  winWidth = $(window).width();
  winHeight = $(window).height();

  projection = d3.geo.mercator()
      .translate([0, 0])
      .scale(winWidth / 2 / Math.PI);

  zoom = d3.behavior.zoom()
      .scaleExtent([1, 50])
      .on("zoom", manageMap);

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

  svg = d3.select("#map").append("svg")
      .attr("viewBox", "0 0 " + winWidth + " " + winHeight)
      .attr("preserveAspectRatio", "xMidYMid meet")
      .append("g")
      .attr("transform", "translate(" + winWidth / 2 + "," + winHeight / 2 + ")")
      .call(zoom);

  g = svg.append("g");

  d3.json("world-50m.json", function(error, world) {
    g.append("path")
        .datum(topojson.feature(world, world.objects.countries))
        .attr("class", "land")
        .attr("d", path);

    g.append("path")
        .datum(topojson.mesh(world, world.objects.countries, function(a, b) { return a !== b; }))
        .attr("class", "boundary")
        .attr("d", path);
  });

function manageMap() {

  var t = d3.event.translate,
      s = d3.event.scale;

  t[0] = Math.min(winWidth / 2 * (s - 1), Math.max(winWidth / 2 * (1 - s), t[0]));
  t[1] = Math.min(winHeight / 2 * (s - 1) + 230 * s, Math.max(winHeight / 2 * (1 - s) - 230 * s, t[1]));

  zoom.translate(t);
  g.style("stroke-width", 1/s).attr("transform", "translate(" + t + ")scale(" + s + ")");
  svg.select("g").selectAll("circle")
      .attr("cx", function(d) { return projection([d.lng, d.lat])[0]; })
      .attr("cy", function(d) { return projection([d.lng, d.lat])[1]; })
      .attr("r", 11/s);

}

在缩放和平移 map 时,是否有任何简单的方法来获取当前可见区域坐标?我已经在尝试投影 map 的翻译,但只是得到了一些奇怪的数字。

最佳答案

这样就可以了。我也把它放在 http://bl.ocks.org/sfinktah/1d38c8a268d893d769ed 上了

即使您已经找到了您的解决方案,这也可能对 future 的 google 员工有用。

function getScreenBounds() {
  return [getPoint(0,0), getPoint()];
}

function getPoint(x,y) {
  if (x == null) x = winWidth;
  if (y == null) y = winHeight;
  var container = g.node();
  var svg = container.ownerSVGElement || container;
  var point = svg.createSVGPoint();
  point.x = x, point.y = y;
  point = point.matrixTransform(container.getScreenCTM().inverse());
  return formatLocation(projection.invert([point.x, point.y]), zoom.scale());
}

function formatLocation(p, k) {
  var format = d3.format("." + Math.floor(Math.log(k) / 2 - 2) + "f");
  return (p[1] < 0 ? format(-p[1]) + "°S" : format(p[1]) + "°N") + " "
       + (p[0] < 0 ? format(-p[0]) + "°W" : format(p[0]) + "°E");
}

关于javascript - D3 map 可见区域坐标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21215487/

相关文章:

javascript - 如何在鼠标进入 div 时运行函数,反之亦然?

javascript - JS,使用xlink将svg保存为png错误:href

javascript - D3js 单条形图通过 slider 更新

javascript - 如何根据用户输入更新 D3 SVG 图表

javascript - 使用 JQuery 替换文本

javascript - AngularJS 不用 JQuery 获取元素属性

javascript - 3d 三 Angular 方程

javascript - onkeypress 无法以表单形式运行

javascript - 如何使用 d3 v4 读取 CSV?

javascript - 如何在误差条图 d3.js 上显示数字