LoginSignup
0
0

More than 1 year has passed since last update.

GeoJSON(ライン)からsource, targetをペアにした配列を作る

Last updated at Posted at 2022-01-19

地図ライブラリにラインデータを渡す際に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
		]
	}
]
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