【问题标题】:react-leaflet map is not correcly displayed in Ionic 5react-leaflet 地图在 Ionic 5 中未正确显示
【发布时间】:2020-10-07 10:13:13
【问题描述】:

当我尝试在移动视图中显示地图时,我看到地图损坏:

https://stackoverflow.com/a/36257493/13739566 - 在这个链接中是 描述为什么它不起作用但在我的情况下使用'invalidSize()'不起作用(或者我可能用错了)。这是我的代码:

import React from 'react';
import { IonContent, IonApp, IonHeader} from '@ionic/react';

import { Map as Maps, Marker, Popup, TileLayer, } from 'react-leaflet'

import 'leaflet/dist/leaflet.css'
import './MainTab.css';

const MainTab: React.FC = () => {

  return (
    <IonApp>
      <IonContent>
        <IonHeader>Header</IonHeader>

        <Maps center={position} zoom={13} keyboard={0} >

        <TileLayer
      url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
    />
        <Marker position={position}>
    <Popup>Kliknij aby przejść do googla: </Popup>
    </Marker>
  </Maps>

        </IonContent>
  </IonApp>
  );
};

export default MainTab;

【问题讨论】:

  • 你导入了leaflet.css。这是不导入时的经典问题。
  • 是的,我做到了,但它仍然不起作用

标签: reactjs ionic-framework leaflet react-leaflet ionic5


【解决方案1】:

我补充:

...
const mapRef = useRef(null)
useEffect(()=>{
      
      const map = mapRef.current.leafletElement; 
      map.invalidateSize()
     }
     )

我在 Maps 的 ref 中使用了 mapRef,它对我有用

【讨论】:

    【解决方案2】:

    即使使用useEffect() 我也无法更正地图。所以,我观察到了onload() 事件。

    import { Map, TileLayer, Marker } from 'react-leaflet';
    import { LatLngTuple } from 'leaflet';
    
    import 'leaflet/dist/leaflet.css';
    
    const defaultLatLng: LatLngTuple = [-7.19207, -48.20779];
    const zoom: number = 14;
    
    const LeafletMap: React.FC = () => {
    
    // ...
    
    const refMap = useRef<Map>(null);
    
    const startMap = useCallback(() => {
        refMap.current?.leafletElement.invalidateSize();
        setTimeout(() => {
          setLoading(false);
        }, 250);
      }, []);
    
      useEffect(() => {
        document.addEventListener('deviceready', startMap, false);
        window.addEventListener('load', startMap, false);
      });
    
    // ...
    
    <Map
      ref={refMap}
      center={defaultLatLng}
      zoom={zoom}
    >
        <TileLayer
          url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
          attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
        ></TileLayer>
    </Map>
    
    }
    

    我还没有找到更好的方法。

    【讨论】:

      猜你喜欢
      • 2021-11-02
      • 2021-01-05
      • 1970-01-01
      • 2021-07-11
      • 1970-01-01
      • 1970-01-01
      • 2021-03-04
      • 2023-02-05
      • 1970-01-01
      相关资源
      最近更新 更多