4
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Next.js+Leafletで地図を表示する

Posted at

Next.jsの導入は完了している物とします。

必要なモジュールをインストール

yarn add leaflet react-leaflet
yarn add -D @types/leaflet

マップコンポーネントとページの作成

ファイルはこんな感じに src/app/testmap 配下へ作成するイメージです。
nextjs_leaflet_project_file.png

マーカーアイコンの読み込み不良の解消

マップコンポーネントを作成する前に、マーカーの読み込みが上手くいかない問題を解消する。

initLeaflet.ts
import Leaflet from 'leaflet';
import markerIcon2x from 'leaflet/dist/images/marker-icon-2x.png';
import markerIcon from 'leaflet/dist/images/marker-icon.png';
import markerIconShadow from 'leaflet/dist/images/marker-shadow.png';

const DefaultIcon = Leaflet.icon({
  iconUrl: markerIcon.src,
  iconRetinaUrl: markerIcon2x.src,
  shadowUrl: markerIconShadow.src,
  iconAnchor: [12, 41], // アイコンのオフセット
  popupAnchor: [0, -32], // ポップアップのオフセット
});
Leaflet.Marker.prototype.options.icon = DefaultIcon;

マップコンポーネント

スタイルシートが無いと表示されないので作成する。

simpleMap.css
/* 地図を画面全体に表示 */
.leaflet-container {
  width: 100vw;
  height: 100vh;
}

/* 通常カーソル */
.leaflet-grab {
  cursor: auto;
}

マップコンポートネントを作成。マーカーは福岡タワーに設定。

simpleMap.ts
import { LatLng } from 'leaflet';
import 'leaflet/dist/leaflet.css';
import { MapContainer, Marker, Popup, TileLayer } from 'react-leaflet';
import './initLeaflet';
import './simpleMap.css';

const simpleMap = () => {
  const position = new LatLng(33.59337, 130.35152); // 福岡タワー

  return (
    <MapContainer center={position} zoom={13}>
      <TileLayer
        attribution='© <a href="https://maps.gsi.go.jp/development/ichiran.html">国土地理院</a>'
        url="https://cyberjapandata.gsi.go.jp/xyz/std/{z}/{x}/{y}.png"
      />
      <Marker position={position}>
        <Popup>
          PopUp!! PopUp!! PopUp!! <br /> ポップアップ
        </Popup>
      </Marker>
    </MapContainer>
  );
};

export default simpleMap;

ページ

作成したマップコンポーネントを読み込むわけですが、クライアントサイドでしか動かないので、ダイナミックインポートする。

page.ts
'use client';

import dynamic from 'next/dynamic';

import { useMemo } from 'react';

export default function Home() {
  const SimpleMap = useMemo(
    () =>
      dynamic(() => import('./simpleMap'), {
        loading: () => <p>map loading...</p>,
        ssr: false,
      }),
    []
  );
  return <SimpleMap />;
}

実行する

実行して http://localhost:3000/testmap にアクセスするとこんな感じに表示されます。
nextjs_leaflet.png

4
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?