I am importing an external SVG using the code below and I have attached zoom and pan behavior to it, which is working fine.
I have also created a type of minimap, which shows the same SVG, but only as a smaller version.
I would like to show a rectangle on the minimap that represents the current viewport shown on the screen. However, I am having trouble with the correct scaling and positioning.
JS CODE:
let url = 'https://gist.githubusercontent.com/ivanbacher/11cd328411c74b2bc2ec789291852544/raw/bb39be70f71e4fb52ae5101150f5fffde4b66272/map.svg';
d3.svg(url).then( (xml)=> {
let width = parseInt( d3.select('body').style('width') );
let height = parseInt( d3.select('body').style('height') );
document.querySelector('#map').appendChild(xml.documentElement.cloneNode(true));
document.querySelector('#minimap').appendChild(xml.documentElement.cloneNode(true));
let map = d3.select('#map').select('svg')
let minimap = d3.select('#minimap').select('svg')
.attr('width', 200);
let transform = d3.zoomIdentity.translate(0, 0).scale(1);
let zoom = d3.zoom()
.scaleExtent([1, 3])
.on('zoom', zoomed);
map.call(zoom)
.call(zoom.transform, transform);
function zoomed() {
let mapMainContainer = map.select('#main_container')
.attr('transform', d3.event.transform);
minimap.select('#minimapRect').remove();
let mapWidth = parseFloat( d3.select('#map').style('width') );
let mapHeight = parseFloat( d3.select('#map').style('height') );
let minimapWidth = parseFloat( d3.select('#minimap').style('width') );
let minimapHeight = parseFloat( d3.select('#minimap').style('height') );
let minimapScale = minimapWidth / mapWidth ; // size of big map times this = size of minimap
let minimapRect = minimap.append('rect')
.attr('id', 'minimapRect')
.attr('width', minimapWidth / minimapScale) //HERE?
.attr('height', minimapHeight / minimapScale ) //HERE?
.attr('stroke', 'red')
.attr('fill', 'black')
.attr('transform', `translate(${-d3.event.transform.x},${-d3.event.transform.y}) scale(${d3.event.transform.k})`);
}
})
Here is a working version of the code + pan and zoom behaviours.
