设置初始D3变换属性

时间:2018-01-19 19:59:38

标签: javascript d3.js mouseevent transform geojson

我通过将shapefile转换为JSON,然后映射它来创建华盛顿特区道路地图。我已经设置了缩放属性以允许用户放大和缩小。它在这里:

https://bl.ocks.org/KingOfCramers/raw/c8d575fb1322590012323a7953908d5f/56bd68ec204046076114413ef777706726bdb50a/

然而,我遇到了问题,因为当用户"缩放"在投影的地图上,它会跳回到屏幕中间。这必须与zoom事件最初接收的坐标有关。如何更改这些设置,以便在交互时,地图开始从当前位置缩放?

这里是完整的代码:

var transLat = -100;
var transLon = -350;
var transScale = 1.6;
var width = 960;
var height = 600;
var margin = {top: 0, bottom: 0, left: 0, right: 0}

d3.queue()
    .defer(d3.json, "simpleroads.json")
        .defer(d3.csv, "locations.csv")
    .await(ready)

function ready(error, world, locations) {
  var projection = d3.geoIdentity().reflectY(true).fitSize([width,height],world)
  var path = d3.geoPath().projection(projection) // Geopath generator
  var zoomExtent = d3.zoom().scaleExtent([1.6, 3]);

  function zoom() {
    g.attr("transform", d3.event.transform)
  }

  console.log(locations)

  var svg = d3.select("body").append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.bottom + margin.top)
    .style("background-color","lightgrey")
    .call(zoomExtent
        .on("zoom", zoom))

  var g = svg.append("g")
      .attr("class", "mapInformation")
        .attr("transform", `translate(${transLat},${transLon}) scale(${transScale})`)
  var paths = g.selectAll("path")
      .data(world.features)
      .enter()
      .append("path")
      .attr("d", path)

}

1 个答案:

答案 0 :(得分:3)

您必须将初始变换传递给缩放功能。在你的情况下:

.call(zoomExtent.transform, 
    d3.zoomIdentity.translate(transLat, transLon).scale(transScale));

以下是更新后的版块内容:http://blockbuilder.org/anonymous/b1d7dcc08c3fbee934fd415d7127dd14