Search code examples
javascriptd3.jsmouseeventtransformgeojson

Setting Initial D3 Transform Properties


I've created a map of Washington D.C. roads by converting a shapefile to JSON, and then mapping it. I have set up a zoom property to allow users to zoom in and out. It's here:

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

However, I'm having problems because when the user "zooms" in on the projected map, it jumps back to the middle of the screen. This must have something to do with the coordinates the zoom event initially receives. How do I change those settings so that, upon interaction, the map begins to zoom from its current position?

Here's the full code:

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)

}

Solution

  • You have to pass the initial transform to the zoom function. In your case:

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

    Here is the updated blockbuilder: http://blockbuilder.org/anonymous/b1d7dcc08c3fbee934fd415d7127dd14