Way on OSM => GeoJSON => Leaflet

yes
yes
Aug 8, 2017 · 4 min read

標題的中文是
把 OSM 上的路線 (way) 轉成 GeoJSON 後再用 Leaflet 畫到網頁上

雪山圈谷

今天要來練習畫雪山圈谷到雪山主峰間的路線

雖然喜歡在網站上寫地圖相關的 code,但工作上一直都沒什麼機會能碰得深入(和 d3 的情況很像),通常只會用到 marker、popup、clustering 等常見的而已,所以其他的就只好在 side project 邊做邊研究了。

剛好最近 side project 很需要在網站上畫出登山路線,於是就來練習一下

  1. 從 OSM 取得登山路線的資料
  2. 把 OSM 的路線資料轉成 GeoJSON
  3. 把路線的 GeoJSON 用 Leaflet 畫在網頁上

從 OSM 取得登山路線的資料

首先,在 OpenStreetMap 上找出雪山圈谷到雪山主峰間路線 (way) 的 id 為 464086143。

way id = 464086143

接著利用 overpass turbo 把資料取出來。

[out:json];
way(464086143)
(around: 200000, 23.825623, 120.982937);
(._;>;);
out;
右邊的 json 就是 way 的 osm data

把 OSM 的路線資料轉成 GeoJSON

利用 osmtogeojson,輕易地就可以把 osm data 轉成 GeoJSON。
而且因為他有 javascript 的 library,所以之後要程式化也很方便。

轉出來的 GeoJSON 還可以到 GeoJSONLint preview 一下。


把路線的 GeoJSON 用 Leaflet 畫在網頁上

最後,利用 Leaflet 的 geoJSON(),可以輕易地把 GeoJSON 型態的 data 畫出來,options 也提供了調整 style 的功能,以及方便加入 tooltip 或 popup 的地方,至於如何把 Leaflet 放到 React 的 Project 中就不在這裡說明了。

L.geoJSON(path.geojson, {
style: {
color: "blue",
weight: 4,
dashArray: "5,15"
},
onEachFeature: this.onEachFeature
}).addTo(this.map);
onEachFeature(feature, layer) {
layer.bindTooltip("雪山圈谷 <=> 雪山主峰").openTooltip([lat, lng]);
}

大功告成~
By the way,CodeSandbox 好有質感豪厲害呀!

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade