Skip to content

Instantly share code, notes, and snippets.

@veltman
Created September 13, 2016 19:34
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 veltman/320dbea8bb2c3c837e137a9381147ac8 to your computer and use it in GitHub Desktop.
Save veltman/320dbea8bb2c3c837e137a9381147ac8 to your computer and use it in GitHub Desktop.
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