Reputation: 53
How to feed JSON data of coordinates to turf.polygon?
Example: turf.polygon();
var polygon = turf.polygon([[
[-2.275543, 53.464547],
[-2.275543, 53.489271],
[-2.215118, 53.489271],
[-2.215118, 53.464547],
[-2.275543, 53.464547]
]], { name: 'poly1', population: 400});
Example: JSON form
var json =
{
"type": "geojson",
"data":
{
"type": "FeatureCollection",
"features": [{
"type": "Feature",
"geometry": {
"type": "Polygon",
"coordinates": [[
[1.275543, 54.464547], // I want to feed these coordinates
[1.275543, 54.489271],
[1.215118, 54.489271],
[1.215118, 54.464547],
[1.275543, 54.464547]
]]
}
}]
}
}
My pseudo code: that doesn't work and returns an error message of "LinearRing of a Polygon must have 4 or more Positions."
var polygon = turf.polygon([[ json.data.features[0].geometry.coordinates ]], { name: 'poly1', population: 400});
Thank you.
Upvotes: 5
Views: 7116
Reputation: 370789
The coordinates
property is already a deeply nested array:
"coordinates": [[
[1.275543, 54.464547], // I want to feed these coordinates
[1.275543, 54.489271],
[1.215118, 54.489271],
[1.215118, 54.464547],
[1.275543, 54.464547]
]]
When you do this:
var polygon = turf.polygon([[
json.data.features[0].geometry.coordinates
]], ...
it will resolve to:
var polygon = turf.polygon([[
[[
[1.275543, 54.464547], // I want to feed these coordinates
[1.275543, 54.489271],
[1.215118, 54.489271],
[1.215118, 54.464547],
[1.275543, 54.464547]
]]
]], ...
You want to extract and use the original nested array itself, without modifications. Try this:
var polygon = turf.polygon(json.data.features[0].geometry.coordinates, { name: 'poly1', population: 400});
Upvotes: 1