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】mapbox で Polygon を read / write / update

Last updated at Posted at 2025-09-06

React の画面上にマップを表示できるライブラリ mapbox で、地図内にポリゴンを読み込み、編集、追加、ポリゴンの GeoJSON を取得するロジックを作成したので、備忘録として記載しておきます。
作成したサンプルは、以下ページにデプロイしてあります

デモ(gif)

こんな感じで動かすことができます

無題のビデオ ‐ Clipchampで作成 (1).gif

package.json

以下ライブラリの追加が必要です。

package.json
"dependencies": {
  "@mapbox/mapbox-gl-draw": "^1.5.0",
  "maplibre-gl": "^5.7.1",
  "react-map-gl": "^8.0.4"
},
"devDependencies": {
  "@types/mapbox__mapbox-gl-draw": "^1.4.9",
}

コード

Map のコンポーネント
※視覚的に見やすい様に <Source><Layer> を追加してありますが、この二つは無くても動きます

MapViewer を実装しているページ
useEffect()console.log("polygons updated:", polygons);してあるので、開発者ツールのコンソールで、画面上に描写中の GeoJSONが確認できる様になっています。

実装時のポイント

ポイントとしては、react-map-gl/maplibre<Map>onLoadMapboxDrawのインスタンスを.addControl() しているところです。
他のサイトのサンプルだと、Controlを別コンポーネントで実装して<Map>内に配置する、みたいな実装がされていたのですが、それだと、画面の初期表示時に、既存の GeoJSONが読み込めなかったため、その処理のために、onLoadからの処理が必要でした。

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?