Search code examples
angularionic-frameworkd3.js

I can't drag and zoom at the same time in d3.js (Ionic 6: Angular)


Zoom doesn't work when I invoke drag at first. Dragging doesn't work when I call the zoom in the first place.

I am writing these codes with Ionic Framework 6 version (Angular).

const w = window.screen.width;
const h = window.screen.height;

const scl: any = Math.min(w, h) / 2.5;
const sensitivity = 75;

const projection: any = d3.geoOrthographic()
    .scale(scl)
    .translate([ w/2, h/2 ]);

const initialScale = projection.scale();

let path = d3.geoPath()
    .projection(projection);

const svg: any = d3.select('#globe')
    .append('svg')
    .attr('width', w)
    .attr('height', h);

const map = svg.append('g');

const drag: any = d3.drag()
    .on('drag', (event) => {
        const rotate = projection.rotate();
        const k = sensitivity / projection.scale();

        projection.rotate([
            rotate[0] + event.dx * k,
            rotate[1] - event.dy * k
        ]);

        path = d3.geoPath().projection(projection);
        svg.selectAll('path').attr('d', path);
    });

svg.call(drag);

const zoom: any = d3.zoom()
    .scaleExtent([1, 10])
    .on('zoom', (event) => {
        if (event.transform.k > 0.3) {
            projection.scale(initialScale * event.transform.k);
            path = d3.geoPath().projection(projection);
            svg.selectAll('path').attr('d', path);
            map.attr('r', projection.scale());
        } else {
            event.transform.k = 0.3;
        }
    });

svg.call(zoom).on('dblclick.zoom', null);

Thanks in advance.

I tried map.call() instead of hammer.js and svg.call() but I can't run both functions at the same time.


Solution

  • I solved the problem. In d3.js, I added a filter to the zoom and drag, and made them act according to the number of touches.

    Filtering for zoom

    const zoom: any = d3.zoom()
        .filter((event) => event.touches && event.touches.length === 2)
    

    Filtering for drag

    const drag: any = d3.drag()
        .filter((event) => !(event.touches && event.touches.length === 2))
    

    Important: You must call zoom first, then drag.