【问题标题】:Next.js React Leaflet Map not Showing ProperlyNext.js React 传单地图未正确显示
【发布时间】:2021-11-27 23:31:50
【问题描述】:

我有下一张传单地图:

但是没有正确显示任何东西,只有当我拖动地图并且只加载您可以在左上角看到的部分时,作为第二张图片。

我发现错误只发生在第一次渲染时,如果我导航到其他页面而不刷新(下一个链接组件),那么它会正确显示。

我的代码:

import React, { useState } from "react";
import { MapContainer, Marker, Popup, TileLayer } from "react-leaflet";
import "leaflet/dist/leaflet.css";

function Map({ coordinates }) {
   const [position, setPosition] = useState(coordinates);
   return (
      <MapContainer center={position} zoom={100} scrollWheelZoom={false} style={{ height: "500px", width: "100%" }}>
         <TileLayer attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors' url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png" />
         <Marker position={position}>
            <Popup>
               A pretty CSS3 popup. <br /> Easily customizable.
            </Popup>
         </Marker>
      </MapContainer>
   );
}

export default Map;

我已经安装了react-reaflet 和leaflet,我还导入了 CSS 并指定了容器的宽度和高度,正如 Stack Overflow 中的其他解决方案所示,但没有任何效果。

如何在 Next 中导入组件(因为 Leaflet 不支持服务器端渲染):

/**
 * Leaflet makes direct calls to the DOM when it is loaded, therefore React Leaflet is not compatible with server-side rendering.
 * @see https://stackoverflow.com/a/64634759/9244579
 */
const Map = dynamic(() => import("../../components/Map"), {
   loading: () => <p>Map is loading</p>,
   ssr: false, // This line is important. It's what prevents server-side render
});

【问题讨论】:

  • 请用width: 500px试试
  • @FalkeDesign 似乎不起作用:(
  • zoom={100}?对吗?
  • 可能会在leaflet loads incomplete map找到一些线索
  • 是的,我尝试调整缩放但没有@SethLutske

标签: javascript reactjs next.js leaflet react-leaflet


【解决方案1】:

我刚刚解决了这个问题。

我发现,如果我调整窗口大小,地图显示正确,所以我必须每 100 毫秒调用一次 invalidateSize() 函数,以便始终更新屏幕大小,这将首先起作用也渲染。

import React, { useState, useEffect } from "react";
import { MapContainer, Circle, TileLayer } from "react-leaflet";
import "leaflet/dist/leaflet.css";

function Map({ coordinates }) {
   const position = coordinates;
   const fillBlueOptions = { fillColor: "#0484D6" };
   const [map, setMap] = useState(null);

   useEffect(() => {
      if (map) {
         setInterval(function () {
            map.invalidateSize();
         }, 100);
      }
   }, [map]);

   return (
      <MapContainer center={position} zoom={20} scrollWheelZoom={false} style={{ height: "400px", width: "100%" }} whenCreated={setMap}>
         <TileLayer attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors' url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png" />
         <Circle center={position} pathOptions={fillBlueOptions} radius={50} />
      </MapContainer>
   );
}

export default Map;

考虑到您必须将属性 whenCreated={setMap} 添加到 MapContainer 组件。

【讨论】:

    猜你喜欢
    • 2017-03-14
    • 1970-01-01
    • 2019-10-15
    • 2013-12-22
    • 2020-10-07
    • 1970-01-01
    • 2021-12-19
    • 2021-11-02
    相关资源
    最近更新 更多