Skip to content

Commit

Permalink
Merge pull request #729 from Turfjs/lineOffset
Browse files Browse the repository at this point in the history
New module @turf/line-offset
  • Loading branch information
DenisCarriere authored May 24, 2017
2 parents 54f4494 + a82fd5b commit 67ee226
Show file tree
Hide file tree
Showing 25 changed files with 1,720 additions and 0 deletions.
20 changes: 20 additions & 0 deletions packages/turf-line-offset/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
The MIT License (MIT)

Copyright (c) 2017 TurfJS

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
56 changes: 56 additions & 0 deletions packages/turf-line-offset/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
# @turf/line-offset

# lineOffset

Takes a [line](http://geojson.org/geojson-spec.html#linestring) and returns a [line](http://geojson.org/geojson-spec.html#linestring) at offset by the specified distance.

**Parameters**

- `line` **([Geometry](http://geojson.org/geojson-spec.html#geometry) \| [Feature](http://geojson.org/geojson-spec.html#feature-objects)<[LineString](http://geojson.org/geojson-spec.html#linestring)>)** input line
- `offset` **[number](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number)** distance to offset the line (can be of negative value)
- `units` **\[[string](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String)]** can be degrees, radians, miles, kilometers, inches, yards, meters (optional, default `kilometers`)

**Examples**

```javascript
var line = {
"type": "Feature",
"properties": {},
"geometry": {
"type": "LineString",
"coordinates": [[-83, 30], [-84, 36], [-78, 41]]
}
};

var offsetLine = turf.lineOffset(line, 2, 'miles');

//addToMap
var addToMap = [offsetLine, line]
```

Returns **[Feature](http://geojson.org/geojson-spec.html#feature-objects)<[LineString](http://geojson.org/geojson-spec.html#linestring)>** Line offset from the input line

<!-- This file is automatically generated. Please don't edit it directly:
if you find an error, edit the source file (likely index.js), and re-run
./scripts/generate-readmes in the turf project. -->

---

This module is part of the [Turfjs project](http://turfjs.org/), an open source
module collection dedicated to geographic algorithms. It is maintained in the
[Turfjs/turf](https://github.com/Turfjs/turf) repository, where you can create
PRs and issues.

### Installation

Install this module individually:

```sh
$ npm install @turf/line-offset
```

Or install the Turf module that includes it as a function:

```sh
$ npm install @turf/turf
```
33 changes: 33 additions & 0 deletions packages/turf-line-offset/bench.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
const fs = require('fs');
const path = require('path');
const load = require('load-json-file');
const Benchmark = require('benchmark');
const lineOffset = require('./');

const directory = path.join(__dirname, 'test', 'in') + path.sep;
let fixtures = fs.readdirSync(directory).map(filename => {
return {
filename,
name: path.parse(filename).name,
geojson: load.sync(directory + filename)
};
});
// fixtures = fixtures.filter(fixture => fixture.name === 'polygon');

/**
* Benchmark Results
*
* line-horizontal x 1,816,451 ops/sec ±15.31% (62 runs sampled)
* linestring-long x 144,640 ops/sec ±3.35% (82 runs sampled)
* linestring-singleSegmentOnly x 2,649,959 ops/sec ±1.54% (76 runs sampled)
* linestring-straight x 1,857,452 ops/sec ±5.83% (77 runs sampled)
*/
const suite = new Benchmark.Suite('turf-line-offset');
for (const {name, geojson} of fixtures) {
suite.add(name, () => lineOffset(geojson, 100, 'meters'));
}

suite
.on('cycle', e => console.log(String(e.target)))
.on('complete', () => {})
.run();
14 changes: 14 additions & 0 deletions packages/turf-line-offset/index.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
/// <reference types="geojson" />

import {Units} from '@turf/helpers';

type GeometryObject = GeoJSON.GeometryObject;
type Feature<Geom extends GeometryObject> = GeoJSON.Feature<Geom>;
type Geoms = GeoJSON.LineString | GeoJSON.MultiLineString;

/**
* http://turfjs.org/docs/#lineoffset
*/
declare function lineOffset<Geom extends Geoms>(line: Feature<Geom> | Geom, distance: number, units?: Units): Feature<Geom>;
declare namespace lineOffset { }
export = lineOffset;
118 changes: 118 additions & 0 deletions packages/turf-line-offset/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
var meta = require('@turf/meta');
var helpers = require('@turf/helpers');
var getCoords = require('@turf/invariant').getCoords;
var intersection = require('./intersection');
var flattenEach = meta.flattenEach;
var lineString = helpers.lineString;
var multiLineString = helpers.multiLineString;
var distanceToDegrees = helpers.distanceToDegrees;

/**
* Takes a {@link LineString|line} and returns a {@link LineString|line} at offset by the specified distance.
*
* @name lineOffset
* @param {Geometry|Feature<LineString|MultiLineString>} geojson input GeoJSON
* @param {number} distance distance to offset the line (can be of negative value)
* @param {string} [units=kilometers] can be degrees, radians, miles, kilometers, inches, yards, meters
* @returns {Feature<LineString|MultiLineString>} Line offset from the input line
* @example
* var line = {
* "type": "Feature",
* "properties": {
* "stroke": "#F00"
* },
* "geometry": {
* "type": "LineString",
* "coordinates": [[-83, 30], [-84, 36], [-78, 41]]
* }
* };
*
* var offsetLine = turf.lineOffset(line, 2, "miles");
*
* //addToMap
* offsetLine.properties.stroke = "#00F"
* var addToMap = [offsetLine, line]
*/
module.exports = function (geojson, distance, units) {
if (!geojson) throw new Error('geojson is required');
if (distance === undefined || distance === null || isNaN(distance)) throw new Error('distance is required');
var type = (geojson.type === 'Feature') ? geojson.geometry.type : geojson.type;
var properties = geojson.properties;

switch (type) {
case 'LineString':
return lineOffset(geojson, distance, units);
case 'MultiLineString':
var coords = [];
flattenEach(geojson, function (feature) {
coords.push(lineOffset(feature, distance, units).geometry.coordinates);
});
return multiLineString(coords, properties);
default:
throw new Error('geometry ' + type + ' is not supported');
}
};

/**
* Line Offset
*
* @private
* @param {Geometry|Feature<LineString>} line input line
* @param {number} distance distance to offset the line (can be of negative value)
* @param {string} [units=kilometers] units
* @returns {Feature<LineString>} Line offset from the input line
*/
function lineOffset(line, distance, units) {
var segments = [];
var offsetDegrees = distanceToDegrees(distance, units);
var coords = getCoords(line);
var finalCoords = [];
coords.forEach(function (currentCoords, index) {
if (index !== coords.length - 1) {
var segment = processSegment(currentCoords, coords[index + 1], offsetDegrees);
segments.push(segment);
if (index > 0) {
var seg2Coords = segments[index - 1];
var intersects = intersection(segment, seg2Coords);

// Handling for line segments that aren't straight
if (intersects !== false) {
seg2Coords[1] = intersects;
segment[0] = intersects;
}

finalCoords.push(seg2Coords[0]);
if (index === coords.length - 2) {
finalCoords.push(segment[0]);
finalCoords.push(segment[1]);
}
}
// Handling for lines that only have 1 segment
if (coords.length === 2) {
finalCoords.push(segment[0]);
finalCoords.push(segment[1]);
}
}
});
return lineString(finalCoords, line.properties);
}

/**
* Process Segment
* Inspiration taken from http://stackoverflow.com/questions/2825412/draw-a-parallel-line
*
* @private
* @param {Array<number>} point1 Point coordinates
* @param {Array<number>} point2 Point coordinates
* @param {number} offset Offset
* @returns {Array<Array<number>>} offset points
*/
function processSegment(point1, point2, offset) {
var L = Math.sqrt((point1[0] - point2[0]) * (point1[0] - point2[0]) + (point1[1] - point2[1]) * (point1[1] - point2[1]));

var out1x = point1[0] + offset * (point2[1] - point1[1]) / L;
var out2x = point2[0] + offset * (point2[1] - point1[1]) / L;
var out1y = point1[1] + offset * (point1[0] - point2[0]) / L;
var out2y = point2[1] + offset * (point1[0] - point2[0]) / L;
return [[out1x, out1y], [out2x, out2y]];
}
117 changes: 117 additions & 0 deletions packages/turf-line-offset/intersection.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
/**
* https://github.com/rook2pawn/node-intersection
*
* Author @rook2pawn
*/

/**
* AB
*
* @private
* @param {Array<Array<number>>} segment - 2 vertex line segment
* @returns {Array<number>} coordinates [x, y]
*/
function ab(segment) {
var start = segment[0];
var end = segment[1];
return [end[0] - start[0], end[1] - start[1]];
}

/**
* Cross Product
*
* @private
* @param {Array<number>} v1 coordinates [x, y]
* @param {Array<number>} v2 coordinates [x, y]
* @returns {Array<number>} Cross Product
*/
function crossProduct(v1, v2) {
return (v1[0] * v2[1]) - (v2[0] * v1[1]);
}

/**
* Add
*
* @private
* @param {Array<number>} v1 coordinates [x, y]
* @param {Array<number>} v2 coordinates [x, y]
* @returns {Array<number>} Add
*/
function add(v1, v2) {
return [v1[0] + v2[0], v1[1] + v2[1]];
}

/**
* Sub
*
* @private
* @param {Array<number>} v1 coordinates [x, y]
* @param {Array<number>} v2 coordinates [x, y]
* @returns {Array<number>} Sub
*/
function sub(v1, v2) {
return [v1[0] - v2[0], v1[1] - v2[1]];
}

/**
* scalarMult
*
* @private
* @param {number} s scalar
* @param {Array<number>} v coordinates [x, y]
* @returns {Array<number>} scalarMult
*/
function scalarMult(s, v) {
return [s * v[0], s * v[1]];
}

/**
* Intersect Segments
*
* @private
* @param {Array<number>} a coordinates [x, y]
* @param {Array<number>} b coordinates [x, y]
* @returns {Array<number>} intersection
*/
function intersectSegments(a, b) {
var p = a[0];
var r = ab(a);
var q = b[0];
var s = ab(b);

var cross = crossProduct(r, s);
var qmp = sub(q, p);
var numerator = crossProduct(qmp, s);
var t = numerator / cross;
var intersection = add(p, scalarMult(t, r));
return intersection;
}

/**
* Is Parallel
*
* @private
* @param {Array<number>} a coordinates [x, y]
* @param {Array<number>} b coordinates [x, y]
* @returns {boolean} true if a and b are parallel (or co-linear)
*/
function isParallel(a, b) {
var r = ab(a);
var s = ab(b);
return (crossProduct(r, s) === 0);
}

/**
* Intersection
*
* @private
* @param {Array<number>} a coordinates [x, y]
* @param {Array<number>} b coordinates [x, y]
* @returns {Array<number>|boolean} true if a and b are parallel (or co-linear)
*/
function intersection(a, b) {
if (isParallel(a, b)) return false;
return intersectSegments(a, b);
}

module.exports = intersection;
Loading

0 comments on commit 67ee226

Please sign in to comment.