コンテンツにスキップ
JP

パブリックAPI でアイテムを GeoJSON 形式で取得して地図に表示する

更新日

パブリックAPI を使うと、ジオメトリフィールドを持つモデルのアイテムを GeoJSON 形式で取得できます。取得した GeoJSON はそのまま MapLibre GL JS・Leaflet などの地図ライブラリや、Re:Earth Visualizer に渡して表示できます。

パブリックAPI からアイテムを GeoJSON 形式で取得して MapLibre GL JS で地図に表示する HTML のサンプルです。WORKSPACE_IDPROJECT_IDMODEL_ID は、実際の値に置き換えてください。

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Re:Earth CMS パブリックAPI + MapLibre GL JS</title>
<link href="https://unpkg.com/maplibre-gl/dist/maplibre-gl.css" rel="stylesheet" />
<script src="https://unpkg.com/maplibre-gl/dist/maplibre-gl.js"></script>
<style>
body { margin: 0; }
#map { width: 100%; height: 100vh; }
</style>
</head>
<body>
<div id="map"></div>
<script>
const WORKSPACE_ID = "<workspace_id_or_alias>";
const PROJECT_ID = "<project_id_or_alias>";
const MODEL_ID = "<model_id_or_key>";
const map = new maplibregl.Map({
container: "map",
style: "https://tile.openstreetmap.jp/styles/osm-bright-en/style.json",
center: [139.6917, 35.6895],
zoom: 10,
});
const CMS_URL = `https://api.cms.reearth.io/api/p/${WORKSPACE_ID}/${PROJECT_ID}/${MODEL_ID}.geojson`;
map.on("load", async () => {
const resp = await fetch(CMS_URL);
if (!resp.ok) throw new Error(`HTTP ${resp.status}`);
const geojson = await resp.json();
map.addSource("cms-data", { type: "geojson", data: geojson });
map.addLayer({
id: "cms-layer",
type: "circle",
source: "cms-data",
paint: {
"circle-radius": 8,
"circle-color": "#e63946",
},
});
});
</script>
</body>
</html>

地図上に CMS から取得したデータが表示されます。

パブリックAPI から取得した GeoJSON を MapLibre GL JS で表示した地図。日本各地に赤い円マーカーが表示されている

エンドポイントの詳細な仕様については、パブリックAPIリファレンス を参照してください。