0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

React Leafletを使って地図を表示する

0
Posted at

Vite+Reactで環境を構築する

$ npm create vite map-sample -- --template react-swc

必要なパッケージをインストールする

以下のコマンドを実行して、Leaflet本体とReact Leafletをインストールします。

$ npm install leaflet react-leaflet

基本的な地図を表示するコードを作成する

MapContainerに必ず明示的な高さや幅を指定してください。
指定しない場合、地図の高さや幅が0(ゼロ)になっていまい、何も表示されないません。

また、%(パーセント)で指定しないでください。
Reactの初期状態では、親となる要素(Appコンポーネントの div や、さらにその上の body、html、#root)には高さが指定されていません。
このため、以下のような挙動となり、何も表示されません。

地図「親(div)の高さの100%になりたい!」
親(div)「私の高さは中身次第(auto)だけど、中身(地図)の高さが決まってないから高さ0(ゼロ)だよ」
地図「じゃあ私も高さ0(ゼロ)になります…」-> 何も表示されない😯

import { MapContainer, TileLayer, Marker, Popup } from 'react-leaflet';

import 'leaflet/dist/leaflet.css';

export const MapComponent = () => {
  const position = [35.681236, 139.767125];

  return (
    <MapContainer
      center={position}
      zoom={13}
      style={{ height: '100vh', 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={position}>
        <Popup>東京駅</Popup>
      </Marker>
    </MapContainer>
  );
};

開発サーバーを起動する

以下のコマンドを実行して、開発サーバーを起動してください。

$ npm run dev

地図を表示する

コマンドを実行すると、Viteの開発サーバーが起動します。
ブラウザで、「http://localhost:5173/」にアクセスしてください。
東京駅周辺の地図が表示されます。

image.png

以上です。

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?