我有一张带有标记的反应传单地图。当我单击任何标记时,它会居中,并打开一个弹出窗口。这个弹出窗口的高度为 300px,这就是为什么我想将地图中心移至 Y 轴上方 -115px。
这是我的
ChangeView
组件,负责定位地图。
import { useMap } from "react-leaflet/hooks";
const ChangeView = ({
center,
zoom,
}) => {
const map = useMap();
map.setView(center, zoom);
return null;
};
export default ChangeView;
我尝试在地图居中后添加平移,但它没有按我的预期工作。第一个标记正确居中,但是当我移动到其他标记时,居中完全错误。
map.setView(center, zoom).panBy([0, -115]);
我希望地图的中心始终比原始中心低 115 像素,但我不知道该怎么做。
终于找到答案了:
使用
react-leaflet map
中的两种方法我可以移动地图。
我将我的中心(以坐标表示)转换为以 px 为单位的中心。
然后我从 y 轴减去 150px。
现在我将这个新点转换为坐标。
最后我将新的中心移动了150px。
import { useMap } from "react-leaflet/hooks";
const ChangeView = ({
center,
zoom,
}) => {
const map = useMap();
const centerInPx = map.latLngToContainerPoint(center);
const newCenterInPx = {
...centerInPx,
y: centerInPx.y - 150,
};
const newCenterInCoords = map.containerPointToLatLng(newCenterInPx);
map.setView(newCenterInCoords, zoom);
return null;
};
export default ChangeView;