地図ライブラリにラインデータを渡す際にsource, targetをペアにしたデータに変換して渡したいときがあるので、その変換方法のメモ。
もととなるGeoJSON(ライン)
const geojson = {
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"properties": {},
"geometry": {
"type": "LineString",
"coordinates": [
[
-1.0272216796875,
47.97889140226657
],
[
-1.9720458984374998,
47.743017409121826
],
[
-2.537841796875,
48.05605376398125
],
[
-3.1256103515625,
48.03034580796616
],
[
-4.04296875,
48.25759852914997
],
[
-4.290161132812499,
48.36354888898689
]
]
}
}
]
}
変換処理
const result = geojson.features
.map(d => d.geometry.coordinates)
.flat()
.reduce((a,c, i, array)=>{
if(!array[i-1]) return a;
a.push({ source: array[i - 1], target:c})
return a;
},[])
console.log(result)
> [
{
"source": [
-1.0272216796875,
47.97889140226657
],
"target": [
-1.9720458984374998,
47.743017409121826
]
},
{
"source": [
-1.9720458984374998,
47.743017409121826
],
"target": [
-2.537841796875,
48.05605376398125
]
},
{
"source": [
-2.537841796875,
48.05605376398125
],
"target": [
-3.1256103515625,
48.03034580796616
]
},
{
"source": [
-3.1256103515625,
48.03034580796616
],
"target": [
-4.04296875,
48.25759852914997
]
},
{
"source": [
-4.04296875,
48.25759852914997
],
"target": [
-4.290161132812499,
48.36354888898689
]
}
]