Alasdair
Alasdair

Reputation: 1384

How can I convert a turf "intersect" polygon to a Leaflet polygon?

In general, a turf polygon can be converted to Leaflet as per https://gis.stackexchange.com/questions/448435/converting-turf-polygon-to-leaflet-polygon .

But there seems to be a difficulty when the polygon is formed by an intersection. Sometimes the coordinates are embedded thus:

[[[long1, lat1],[long2,lat2], ... ]]

but other times this seems to be embedded one layer further:

[[[[long1, lat1],[long2,lat2], ... ]]]

at least, when displayed with

console.log(JSON.stringify(intersection.geometry.coordinates));

This means that for some turf intersect polygons, the coordinates can be obtained with coordinates[0], but for others I'd need coordinates[0][0].

Is there any straightforward way to manage this? (I've tried using turf.getCoords but it doesn't seem to make any difference.)

Upvotes: 2

Views: 40

Answers (1)

Eric Fortis
Eric Fortis

Reputation: 17360

Check the type of the resulting intersection Feature, which could be creating multiple polygons. Sometimes those extra polygons are artifacts that you can get rid of by rounding to lower precision.

But other times they could be valid polygons you are interested in. Or perhaps, if you are only interested in the largest intersection polygon, you can use turfArea and find the biggest one from the MultiPolygon.

if (feat.geometry.type === 'Polygon')
  coordinates[0]
else // is 'MultiPolygon'
  coordinates[0][0]

I haven't used Leaflet but it looks like you can pass either one (MultiPolygon or Polygon).

Upvotes: 0

Related Questions