admin管理员组文章数量:1316690
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;
}
本文标签: javascriptflyTo function not working with dynamic positionStack Overflow
版权声明:本文标题:javascript - flyTo function not working with dynamic position - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742006413a2412046.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论