地图在使用 react-leaflet 初始化时不可见

IT技术 reactjs leaflet react-leaflet
2021-05-22 13:49:56

我有这个react组件:

import React, { Fragment } from 'react';
import L from 'leaflet';
import { Map, TileLayer, Marker, Popup } from 'react-leaflet';
import 'leaflet/dist/leaflet.css';

const customMarker = new L.icon({
    iconUrl: '/images/poemEditorTools/location-pointer-new.svg',
    iconSize: [56, 72],
    iconAnchor: [26, 72],
}); 

const MyPopupMarker = ({ content, position }) => (
    <Marker position={position} icon={customMarker} >
      <Popup>{content}</Popup>
    </Marker>
)

const MyMarkersList = ({ markers }) => {
    const items = markers.map(({ key, ...props }) => (
        <MyPopupMarker key={key} {...props} />
    ))
    return <Fragment>{items}</Fragment>
}

const markers = [
    { key: 'marker1', position: [51.5, -0.1], content: 'My first popup' },
    { key: 'marker2', position: [51.51, -0.1], content: 'My second popup' },
    { key: 'marker3', position: [51.49, -0.05], content: 'My third popup' },
]

class MapWithPoems extends BaseComponent {
    render() {
        return (
            <Map center={[51.505, -0.09]} zoom={13} style={{ height: "500px", width: "100%" }} >
                <TileLayer
                    url={
                        "https://server.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer/tile/{z}/{y}/{x}"
                    }
                />
                <MyMarkersList markers={markers} />
            </Map>
        );
    }
}

export default MapWithPoems;

问题是当页面被下载时,地图会缩小到容器的左侧。我必须调整窗口大小以使地图以全宽显示。看图片。

在此处输入图片说明

在此处输入图片说明

这里有什么问题?:)

2个回答

您必须map.invalidateSize();在初始化地图后调用

也许这个链接可以帮助你在 reactjs 中使用它:https ://stackoverflow.com/a/56184369/8283938

使用react-hooks。这有效:

const map = useMap()

useEffect(() => {
    setTimeout(() => { 
        map.invalidateSize(); 
    }, 250); 
}, [map])

但这个解决方案对我来说似乎有点棘手。250ms 似乎是任意的。