简体   繁体   中英

react-leaflet with functional components and ImageOverlay

This is my first time using Leaflet, so I've been a bit confused while trying to understand the docs. I am trying to create a custom map with react-leaflet by using the ImageOverlay component. I am struggling to get the Map component size to be the same size as my image. I'm afraid I don't quite understand bounds , but I think that's what I'm supposed to be using here. I tried using getBounds() to see if that can get the bounds I need, but I don't think my implementation with the refs is correct. Here is my code so far:

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.leafElement.getBounds());
    }, []);

    return (
        <Map
            center={initialPos}
            zoom={0}
            ref={mapRef}
            minZoom={0}
            crs={CRS.Simple}
        >
            <ImageOverlay url="https://i.imgur.com/Ion6X7C.jpg" />
        </Map>
    );
};

Logging the new bounds in the useEffect , I get an object that looks like this:

LatLngBounds {
  _southWest: LatLng {lat: -110, lng: -95},
  _northEast: LatLng {lat: 290, lng: 565}
}

But I still get the following error:

Cannot read property 'lat' of undefined

I have referenced this question and this question to help me figure out how to set the bounds in a way that will fit the Map to the size of my image, but have been struggling on converting them to functional components

You are looking for the map instance which can be taken from mapRef.current.leafletElement instead of mapRef.current .

You can achieve that in a more simple way without passing bounds several times as props. Also you cannot extract the map bounds before the component is mounted because simply it has not been initialised therefore it has no center and zoom by the time you are trying to get its bounds. You will receive a relevant error if you tried to get it:

Error Set map center and zoom first.

So you need to create the imageOverlay instance like this using functional component:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM