Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@barnabas-avalara
Last active November 11, 2020 16:54
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save barnabas-avalara/2a9d9be5edd84fe2da8e769a9a9c509e to your computer and use it in GitHub Desktop.
Save barnabas-avalara/2a9d9be5edd84fe2da8e769a9a9c509e to your computer and use it in GitHub Desktop.
TurfJS kink functions
import difference from '@turf/difference'
import { feature, multiPolygon, polygon, featureCollection, multiPoint } from '@turf/helpers'
import { getGeom } from '@turf/invariant'
import { flattenEach, featureEach } from '@turf/meta'
import simplepolygon from 'simplepolygon'
import gpsi from 'geojson-polygon-self-intersections'
export function unkinkPolygon (geojson) {
const features = []
const holes = []
flattenEach(geojson, feature => {
if (feature.geometry.type !== 'Polygon') return
const isects = gpsi(feature, val => val)
if (isects.length < 1) return features.push(feature) // don't run it through simple polygon if it's not really intersecting
// remove the holes and set them aside for later
const holeCoords = feature.geometry.coordinates.splice(1, feature.geometry.coordinates.length - 1)
if (holeCoords.length > 0) holes.push(multiPolygon(holeCoords.map(c => [c])))
featureEach(simplepolygon(feature), poly => {
const newPoly = polygon(poly.geometry.coordinates, feature.properties)
features.push(newPoly)
})
})
// punch the holes back out of the feature
const fixedFeatures = holes.length > 0 ? features.map(feature => {
return holes.reduce((accumulator, hole) => difference(accumulator, hole), feature)
}) : features
return featureCollection(fixedFeatures)
}
export function kinks (geojson) {
const coordinates = []
flattenEach(geojson, function (feature) {
if (feature.geometry.type !== 'Polygon') return
gpsi(feature, isect => { coordinates.push(isect) })
})
return multiPoint(coordinates)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment