我想在 NextJS 14 应用程序中显示传单地图。尝试使其发挥作用会带来以下挑战:
我的依赖项是:
"leaflet": "^1.9.4",
"next": "14.1.0",
"react": "^18",
"react-dom": "^18",
"react-leaflet": "^4.2.1",
最小工作配置的设置是什么?
我在 Stackoverflow 和 Github 上搜索了好的解决方案。我最终找到了我需要知道的一切,但收集所有信息花了一些时间。
因此,我想在一篇文章中提供所有必要的信息。
为了实现此目的,我们需要 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。顺序很重要!创建一个地图组件并确保在其上设置width和height。
组件/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='© <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>
);
}