Northbret
Northbret

Reputation: 3

flyTo function not working with dynamic position

I'm working on a react project, where I display some markers on a leaflet map. I added two buttons on my map. One of them should fly to the position of the selected marker, when I click it. Therefor I pass the position of the marker (implemented as a state variable in my main component) to the button component and use it in my onClick function.

Till then everything works, it also flies to my default position, when no marker is selected, but when I change the marker (and so the position) and click the button, it's not flying to the desired position.

import {useEffect} from "react";
import {createRoot} from "react-dom/client";
import {useMap} from "react-leaflet";
import L from "leaflet";
import locateIcon from '../assets/my-location.svg'
import routeIcon from '../assets/route.svg'
import '../components/IconButton.css'

export default function CustomControls({position}) {

    // Add icons
    const LocateControlIcon = () => <img src={locateIcon}/>;
    const RouteControlIcon = () => <img src={routeIcon}/>;

    const map = useMap();

    // Functionality buttons
    function handleLocateButton() {
        console.log('Fly to: ' + position);
        map.flyTo(position);
    }

    function handleRouteButton() {
        alert('Button clicked!');
    }

    useEffect(() => {

        const CustomControl = L.Control.extend({
            position: "topright",

            onAdd: () => {
                const container = L.DomUtil.create('div', 'custom-control');
                container.style.margin = '16px 16px 0 0';

                const locateButton = L.DomUtil.create('button', 'icon-button', container);
                locateButton.onclick = handleLocateButton;

                const routeButton = L.DomUtil.create('button', 'icon-button', container);
                routeButton.style.margin = '8px 0 0 0';
                routeButton.onclick = handleRouteButton;

                // Render icons in the buttons
                createRoot(locateButton).render(<LocateControlIcon/>);
                createRoot(routeButton).render(<RouteControlIcon/>);

                L.DomEvent.disableClickPropagation(container);

                return container;
            },
        });

        const controlInstance = new CustomControl();
        map.addControl(controlInstance);

        return () => {
            map.removeControl(controlInstance);
        };

    }, [map]);

    return null;
}

Upvotes: 0

Views: 51

Answers (0)

Related Questions