Created
September 13, 2016 19:34
-
-
Save veltman/320dbea8bb2c3c837e137a9381147ac8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var slice = require("turf-line-slice-at-intersection"), | |
buffer = require("turf-buffer"), | |
pip = require("point-in-polygon"); | |
module.exports = function(feature, boundary) { | |
var lineStrings = coerceLineStrings(feature), | |
results = []; | |
poly = buffer(coercePolygon(boundary), 50, "degrees"); | |
lineStrings.forEach(function(ls){ | |
var sliced = slice(ls, poly), | |
inside = pip(ls.geometry.coordinates[0], poly.geometry.coordinates[0]); | |
sliced.features.forEach(function(d,i){ | |
if ((inside && i % 2 === 0) || (!inside && i % 2)) { | |
results.push(d.geometry.coordinates); | |
} | |
}); | |
}); | |
return { | |
type: "MultiLineString", | |
coordinates: results | |
}; | |
}; | |
function coercePolygon(feature) { | |
if (Array.isArray(feature)) { | |
feature = { | |
type: "Polygon", | |
coordinates: [feature] | |
}; | |
} | |
return feature.type === "Feature" ? feature : { type: "Feature", properties: {}, geometry: feature }; | |
} | |
function coerceLineStrings(feature) { | |
var coordinates; | |
if (feature.type === "Feature") { | |
feature = feature.geometry; | |
} | |
if (feature.type === "MultiLineString") { | |
coordinates = feature.coordinates; | |
} else { | |
coordinates = [feature.coordinates]; | |
} | |
return coordinates.map(function(ls){ | |
return { | |
type: "Feature", | |
geometry: { | |
type: "LineString", | |
coordinates: ls | |
} | |
}; | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment