svg - 我如何使用 SVG translate 将 d3.js 投影居中到给定的纬度和经度值?

标签 svg maps d3.js geo

我正在使用 d3 渲染 GeoJSON 世界地图的墨卡托投影。

我希望能够在用户逐步浏览我的应用程序时使用 d3 缩放并将 map 转换为已知的纬度和经度值。

projection.center ( https://github.com/mbostock/d3/wiki/Geo-Projections#wiki-center ) 与 transition().duration() 相结合,做我想做的事,但这需要重新绘制 map ,因此继续重复似乎很昂贵。我想使用 SVG ( https://developer.mozilla.org/en-US/docs/SVG/Attribute/transform) 附带的原生 translate()scale() 方法。

我找到了一些有用的例子,比如 Mike Bostock 的 ( http://bl.ocks.org/mbostock/4699541 ),还有一些有用的问题,比如下面关于将 map 以给定的 GeoJSON 对象 ( Center a map in d3 given a geoJSON object ) 为中心的问题,但我正在努力总结我的绕过他们。

有人可以帮助我使用 SVG 的 transform="translate(x, y)" 将我的投影集中到给定的纬度和经度值吗?

非常感谢。


编辑 @Lars:首先,谢谢。我已经尝试过你的建议,并且发生了移动,但投影似乎移动得太远了。我在下面附上了屏幕截图和我的投影代码:

var SFMap = {
    initialise: function() {
        var width = "752";
        var height = "420";
        SFMap.projection = d3.geo.mercator()
            .scale(100)
            .translate([width/2, height/2])
            .center([0, 0]);

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

        SFMap.svg = d3.select("#sf__map")
            .append("svg")
            .attr("width", width)
            .attr("height", height);

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

        d3.json("world-110m.topo.json", SFMap.draw);
    },

    draw: function(error, topology) {
        SFMap.g
            .selectAll("path")
            .data(topojson.feature(topology, topology.objects.countries)
                .features)
            .enter()
            .append("path")
            .attr("d", SFMap.path)
            .attr("class", "feature");
    },

Projection movement (View full size)

翻译到伦敦 - 51.5171° N, 0.1062° W - 使用以下代码时会发生上述情况:

var coordinates = SFMap.projection([0.1062, 51.5171]);
SFMap.g.attr("transform", "translate(" + (-coordinates[0]) + "," + (-coordinates[1]) + ")");

我还尝试了第二次反转值。

最佳答案

假设您的投影中心是 (0,0),您需要做的就是将您想要居中的点的坐标提供给您的投影函数(以转换为用户坐标)并给出倒数翻译。有点像

var coordinates = projection(point);
svg.attr("transform", "translate(" + (-coordinates[0]) + "," + (-coordinates[1]) + ")");

如果您也翻译了投影,则需要考虑到这一点,例如

svg.attr("transform", "translate(" + (-coordinates[0]+width/2) +
         "," + (-coordinates[1]+height/2) + ")");

关于svg - 我如何使用 SVG translate 将 d3.js 投影居中到给定的纬度和经度值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16785881/

相关文章:

css - 谁能解释为什么 firefox 裁剪这个 SVG 图像?

css - 将阴影添加到 svg 多边形

javascript - 使用 SVG 和 JS 创建 30 秒计时器显示

php - 从地址字段创建动态谷歌地图链接

Android 谷歌地图在 Nexus S 上崩溃

svg - 在 SVG 中绘制文本但删除背景

ios - 用户 GPS 位置图标问题

javascript - 如何正确使用D3中的call()来绑定(bind)拖动行为?

json - 如何在 D3.js 中动态显示多行文本?

d3.js - 过滤 d3.js sankey 图的数据