具有功能组件和ImageOverlay的反应叶

问题描述 投票:0回答:1

这是我第一次使用Leaflet,因此在尝试理解文档时有些困惑。我正在尝试通过使用ImageOverlay组件来创建带有react-leaflet的自定义地图。我正在努力使Map组件的大小与我的图像相同。恐怕我不太了解bounds,但是我认为这就是我应该在这里使用的。我尝试使用getBounds()来查看是否可以达到所需的界限,但我认为refs的实现不正确。到目前为止,这是我的代码:

import React, { useState, useRef, useEffect } from "react";
import { Map, ImageOverlay } from "react-leaflet";
import { CRS, getBounds } from "leaflet";

export default () => {
    const [bounds, setBounds] = useState([]);
    const mapRef = useRef(null);

    useEffect(() => {
        setBounds(mapRef.current.getBounds());
    }, []);

    return (
        <Map
            ref={mapRef}
            minZoom={0}
            crs={CRS.Simple}
            maxBoundsViscosity={1.0}
            maxBounds={bounds}
            bounds={bounds}
            boundsOptions={{ padding: [50, 50] }}
        >
            <ImageOverlay url="https://i.imgur.com/Ion6X7C.jpg" bounds={bounds} maxBounds={bounds} />
        </Map>
    );
};

上面的代码抛出以下错误:

Cannot read property 'getBounds' of null

[我参考了this questionthis question来帮助我弄清楚如何以适合地图大小的方式设置边界,但一直在努力将其转换为功能组件

reactjs leaflet react-leaflet
1个回答
0
投票

您正在寻找可以从mapRef.current.leafletElement而不是mapRef.current获取的地图实例。

您可以以更简单的方式实现这一目标,而不必多次通过道具。同样,您无法在挂载组件之前提取地图边界,因为它还没有初始化,因此在您尝试获取其边界时没有centerzoom。如果您尝试获取它,将会收到一个相关的错误:

错误设置地图中心并先缩放。

所以您需要使用功能组件像这样创建imageOverlay实例:

const mapRef = useRef(null);

  useEffect(() => {
    const map = mapRef.current.leafletElement;
    const bounds = [[-26.5, -25], [1021.5, 1023]];
    const image = L.imageOverlay("https://i.imgur.com/Ion6X7C.jpg", bounds).addTo(
      map
    );
    // this is what you were looking for
    map.fitBounds(image.getBounds());
  }, []);

Demo

© www.soinside.com 2019 - 2024. All rights reserved.