1

I have the code ready in ReactJS. The code is specifically for generating two maps side by side in a single screen using the react-map-gl and maplibre-gl libraries. Both maps are moving individually. I need to synchronize both maps. Both maps should move and zoom in and zoom out if I move either of them.

I need to use the maplibre-gl because it is without Token.

Problem: Both maps are moving separately.

Looking for: Both maps should be in sync and move together if I try to move either of them.

Snippet for Two Maps using react-map-gl & maplibre-gl:

import * as React from 'react';
import {useState, useCallback, useMemo} from 'react';
import {render} from 'react-dom';
import Map from 'react-map-gl';
import maplibregl from 'maplibre-gl';
import 'maplibre-gl/dist/maplibre-gl.css';

const LIGHT_MAP_STYLE = 'https://tiles.basemaps.cartocdn.com/gl/positron-gl-style/style.json';
const DARK_MAP_STYLE = 'https://tiles.basemaps.cartocdn.com/gl/dark-matter-gl-style/style.json';


const LeftMapStyle= {
    position: 'absolute',
    width: '50%',
    height: 800,
  };
  const RightMapStyle= {
    position: 'absolute',
    left: '50%',
    width: '50%',
    height: 800,
  };

  export default function ExtraDashboards()  {
    const [viewState, setViewState] = useState({
        longitude: -122.43,
        latitude: 37.78,
        zoom: 12,
        pitch: 30
    });

    const [mode, setMode] = useState('side-by-side');
    const [activeMap, setActiveMap] = useState('left');
    const onLeftMoveStart = useCallback(() => setActiveMap('left'), []);
    const onRightMoveStart = useCallback(() => setActiveMap('right'), []);

    const onMove = useCallback(event =>
        setViewState(event.viewState),
    []);
    return (
        <>
            <div style={{ position: 'relative', height: '100%' }}>
                <Map
                    id="left-map"
                    initialViewState={{...viewState}}
                    //padding={leftMapPadding}
                    onMoveStart={onLeftMoveStart}
                    onMove={activeMap === 'left' && onMove}  
                    mapLib={maplibregl}
                    mapStyle={LIGHT_MAP_STYLE}
                    style={LeftMapStyle}
                >
                </Map>
                <Map
                    id="right-map"
                    initialViewState={{...viewState}}
                    //padding={rightMapPadding}
                    onMoveStart={onRightMoveStart}
                    onMove={activeMap === 'right' && onMove}
                    mapLib={maplibregl}
                    mapStyle={DARK_MAP_STYLE}
                    style={RightMapStyle}
                >
                </Map>
            </div>
        </>
    );
}

function renderToDom(container) {
    render(<ExtraDashboards />, container);
}
user7247147
  • 1,045
  • 1
  • 10
  • 24
Rana Hamza
  • 11
  • 2

0 Answers0