最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - flyTo function not working with dynamic position - Stack Overflow

programmeradmin1浏览0评论

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;
}
发布评论

评论列表(0)

  1. 暂无评论