Accepted answer

You are currently constraining the size of the main map to 600px via the enclosing div element, and the mini map to 200px. Note that the coordinate system that both are using will be the same, though. Your calculations need to take into account the difference between the size of the SVG viewBox and the main map size, i.e.

let mapWidth = parseFloat('#map').style('width') );
let mapHeight = parseFloat('#map').style('height') );
let factor = mapWidth /'#map svg').attr('viewBox').split(' ')[2]

The dimensions of the rect on the mini map should be set using this scaling factor:

  let minimapRect = minimap.append('rect')
      .attr('id', 'minimapRect')
      .attr('width', mapWidth / factor )
      .attr('height', mapHeight / factor )

When the zoom events occur, you already have the x and y values and the scale factor, d3.event.transform.k, so you just need to divide everything by the scale factor:

  let dx = d3.event.transform.x / d3.event.transform.k;
  let dy = d3.event.transform.y / d3.event.transform.k;
  let minimapRect = minimap.append('rect')
      .attr('id', 'minimapRect')
      .attr('width', mapWidth / factor / d3.event.transform.k )
      .attr('height', mapHeight / factor / d3.event.transform.k )
      .attr('stroke', 'red')
      .attr('fill', 'black')
      .attr('transform', `translate(${-dx},${-dy})`);


I found another way of achieving the same results using d3.zoomIdentity.scale. Working example

function zoomed() {
      let transform = d3.event.transform;
      let modifiedTransform = d3.zoomIdentity.scale( 1/transform.k ).translate( -transform.x, -transform.y );

      let mapMainContainer ='#main_container')
         .attr('transform', transform);

          .attr('width', mapMainContainer.node().getBBox().width )
          .attr('height', mapMainContainer.node().getBBox().height )
          .attr('stroke', 'red')
          .attr('stroke-width', 10/modifiedTransform.k )
          .attr('stroke-dasharray', 10/modifiedTransform.k )
          .attr('fill', 'none')
          .attr('transform', modifiedTransform);

Related Query

More Query from same tag