React-Leaflet 4 与 NextJS 14 |工作设置

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

我想在 NextJS 14 应用程序中显示传单地图。尝试使其发挥作用会带来以下挑战:

  • NextJS 14 默认使用服务器端渲染(SSR),leaflet 不支持
  • NextJS 14 使用 webpack 进行捆绑,这会弄乱传单中的图标

我的依赖项是:

"leaflet": "^1.9.4",
"next": "14.1.0",
"react": "^18",
"react-dom": "^18",
"react-leaflet": "^4.2.1",

最小工作配置的设置是什么?

我在 Stackoverflow 和 Github 上搜索了好的解决方案。我最终找到了我需要知道的一切,但收集所有信息花了一些时间。

因此,我想在一篇文章中提供所有必要的信息。

next.js react-leaflet
1个回答
0
投票

为了实现此目的,我们需要 leaflet-defaulticon-compatibility。完整的设置如下所示:

npx create-next-app@latest
npm install leaflet react-leaflet leaflet-defaulticon-compatibility
npm install -D @types/leaflet

leaflet
leaflet-defaulticon-compatibility
导入css和js。顺序很重要!创建一个地图组件并确保在其上设置widthheight

组件/Map.tsx

"use client";

// START: Preserve spaces to avoid auto-sorting
import "leaflet/dist/leaflet.css";

import "leaflet-defaulticon-compatibility/dist/leaflet-defaulticon-compatibility.webpack.css";

import "leaflet-defaulticon-compatibility";
// END: Preserve spaces to avoid auto-sorting
import { MapContainer, Marker, Popup, TileLayer, useMap } from "react-leaflet";

export default function Map() {
  const map = useMap();

  return (
      <MapContainer
        preferCanvas={true}
        center={[51.505, -0.09]}
        zoom={11}
        scrollWheelZoom={true}
        style={{ height: "80vh", width: "100vw" }}
      >
        <TileLayer
          attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
          url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
        />
        <Marker position={map.getCenter()}>
          <Popup>
            This Marker icon is displayed correctly with <i>leaflet-defaulticon-compatibility</i>.
          </Popup>
        </Marker>
      </MapContainer>
  );
}

导入地图组件:

应用程序/page.tsx

"use client";

import dynamic from "next/dynamic";

const LazyMap = dynamic(() => import("@/components/Map"), {
  ssr: false,
  loading: () => <p>Loading...</p>,
});

export default function Home() {
  return (
    <main>
      <LazyMap />
    </main>
  );
}
© www.soinside.com 2019 - 2024. All rights reserved.