javascript - D3.js zoomTo 指向二维 map (投影)

标签 javascript d3.js

我在使用 D3 缩放时遇到了一些问题。

我用 D3 和 topoJSON 东西构建了一个 map ,当我搜索一个城市时, map 上会出现一个点。

我使用此代码在我的 map 上进行了限制缩放: http://bl.ocks.org/mbostock/4987520

它对我所有的东西都很好用,现在我尝试通过在搜索后对点添加缩放来改善体验。

我在这里看到了一些有趣的代码:http://bl.ocks.org/mbostock/6242308

但是在两个链接上有两种不同的缩放功能,我不知道如何混合使用。我的代码没有错误,但缩放总是在同一点(我认为是 map 的中心),即使我的点在控制台日志中返回不同的位置....不明白为什么

下面是一些代码示例:

var zoom = d3.behavior.zoom()
    .scaleExtent([1, 30])
    .on("zoom", move);

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

 var svg = d3.select("body").append("svg")
    .attr("width", width)
    .attr("height", height)
    .append("g")
    .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")")
    .call(zoom);

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

//This is called when ajax research
function setPlaces(jsonData){
    ... code stuff
    var point = [authors[0].birth_place.lon, authors[0].birth_place.lat];
    svg.transition().call(zoomTo(point, 4).event);
}

function zoomTo(location, scale) {
    var point = projection(location);
    return zoom
       .translate([width / 2 - point[0] * scale, height / 2 - point[1] * scale])
       .scale(scale);
}

function move() {
var t = d3.event.translate,
        s = d3.event.scale;
t[0] = Math.min(width / 2 * (s - 1), Math.max(width / 2 * (1 - s), t[0]));
t[1] = Math.min(height / 2 * (s - 1) + 230 * s, Math.max(height / 2 * (1 - s) - 230 * s, t[1]));
zoom.translate(t);
g.style("stroke-width", 1 / s).attr("transform", "translate(" + t + ")scale(" + s + ")");
}

最佳答案

您的代码中的主要问题是经度和纬度在缩放到该点的调用中被切换。除此之外,变焦工作正常。然而,当您使用 map 的缩放行为时,通过它设置它比直接通过 SVG 转换更好。相关代码如下。

function zoomTo(location, scale) {
  var point = projection(location);

  zoom.scale(scale);
  zoom.translate([-point[0] * scale, -point[1] * scale]);

  return zoom;
}

关于javascript - D3.js zoomTo 指向二维 map (投影),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20409484/

相关文章:

javascript - 当元素到达某个点时更改 CSS 属性

c# - Javascript C# Unicode 字符串 - headscratcher

javascript - 正则表达式用于字母数字字符,而不仅仅是数字

javascript - 操作 HTML 中的路径元素

javascript - D3-桑基错误 : Missing: (nodename)

javascript - 如何停止backbone.js中的传播

php - 为什么我的 <script> 标签在 php 文件中不起作用? (这里也涉及到 jQuery)

jquery - 为 d3 map 上的点击事件设置颜色

javascript - D3 Multi Line Chart- 多数组,解析时间戳

javascript - svg 圆圈没有很好地注册鼠标悬停