plotly.js
Version:
The open source javascript graphing library that powers plotly
1,337 lines (1,297 loc) • 3.57 MB
JavaScript
/**
* plotly.js (mapbox) v1.58.4
* Copyright 2012-2020, Plotly, Inc.
* All rights reserved.
* Licensed under the MIT license
*/
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.Plotly = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(_dereq_,module,exports){
'use strict';
var Lib = _dereq_('../src/lib');
var rules = {
"X,X div": "direction:ltr;font-family:'Open Sans', verdana, arial, sans-serif;margin:0;padding:0;",
"X input,X button": "font-family:'Open Sans', verdana, arial, sans-serif;",
"X input:focus,X button:focus": "outline:none;",
"X a": "text-decoration:none;",
"X a:hover": "text-decoration:none;",
"X .crisp": "shape-rendering:crispEdges;",
"X .user-select-none": "-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;-o-user-select:none;user-select:none;",
"X svg": "overflow:hidden;",
"X svg a": "fill:#447adb;",
"X svg a:hover": "fill:#3c6dc5;",
"X .main-svg": "position:absolute;top:0;left:0;pointer-events:none;",
"X .main-svg .draglayer": "pointer-events:all;",
"X .cursor-default": "cursor:default;",
"X .cursor-pointer": "cursor:pointer;",
"X .cursor-crosshair": "cursor:crosshair;",
"X .cursor-move": "cursor:move;",
"X .cursor-col-resize": "cursor:col-resize;",
"X .cursor-row-resize": "cursor:row-resize;",
"X .cursor-ns-resize": "cursor:ns-resize;",
"X .cursor-ew-resize": "cursor:ew-resize;",
"X .cursor-sw-resize": "cursor:sw-resize;",
"X .cursor-s-resize": "cursor:s-resize;",
"X .cursor-se-resize": "cursor:se-resize;",
"X .cursor-w-resize": "cursor:w-resize;",
"X .cursor-e-resize": "cursor:e-resize;",
"X .cursor-nw-resize": "cursor:nw-resize;",
"X .cursor-n-resize": "cursor:n-resize;",
"X .cursor-ne-resize": "cursor:ne-resize;",
"X .cursor-grab": "cursor:-webkit-grab;cursor:grab;",
"X .modebar": "position:absolute;top:2px;right:2px;",
"X .ease-bg": "-webkit-transition:background-color 0.3s ease 0s;-moz-transition:background-color 0.3s ease 0s;-ms-transition:background-color 0.3s ease 0s;-o-transition:background-color 0.3s ease 0s;transition:background-color 0.3s ease 0s;",
"X .modebar--hover>:not(.watermark)": "opacity:0;-webkit-transition:opacity 0.3s ease 0s;-moz-transition:opacity 0.3s ease 0s;-ms-transition:opacity 0.3s ease 0s;-o-transition:opacity 0.3s ease 0s;transition:opacity 0.3s ease 0s;",
"X:hover .modebar--hover .modebar-group": "opacity:1;",
"X .modebar-group": "float:left;display:inline-block;box-sizing:border-box;padding-left:8px;position:relative;vertical-align:middle;white-space:nowrap;",
"X .modebar-btn": "position:relative;font-size:16px;padding:3px 4px;height:22px;cursor:pointer;line-height:normal;box-sizing:border-box;",
"X .modebar-btn svg": "position:relative;top:2px;",
"X .modebar.vertical": "display:flex;flex-direction:column;flex-wrap:wrap;align-content:flex-end;max-height:100%;",
"X .modebar.vertical svg": "top:-1px;",
"X .modebar.vertical .modebar-group": "display:block;float:none;padding-left:0px;padding-bottom:8px;",
"X .modebar.vertical .modebar-group .modebar-btn": "display:block;text-align:center;",
"X [data-title]:before,X [data-title]:after": "position:absolute;-webkit-transform:translate3d(0, 0, 0);-moz-transform:translate3d(0, 0, 0);-ms-transform:translate3d(0, 0, 0);-o-transform:translate3d(0, 0, 0);transform:translate3d(0, 0, 0);display:none;opacity:0;z-index:1001;pointer-events:none;top:110%;right:50%;",
"X [data-title]:hover:before,X [data-title]:hover:after": "display:block;opacity:1;",
"X [data-title]:before": "content:'';position:absolute;background:transparent;border:6px solid transparent;z-index:1002;margin-top:-12px;border-bottom-color:#69738a;margin-right:-6px;",
"X [data-title]:after": "content:attr(data-title);background:#69738a;color:white;padding:8px 10px;font-size:12px;line-height:12px;white-space:nowrap;margin-right:-18px;border-radius:2px;",
"X .vertical [data-title]:before,X .vertical [data-title]:after": "top:0%;right:200%;",
"X .vertical [data-title]:before": "border:6px solid transparent;border-left-color:#69738a;margin-top:8px;margin-right:-30px;",
"X .select-outline": "fill:none;stroke-width:1;shape-rendering:crispEdges;",
"X .select-outline-1": "stroke:white;",
"X .select-outline-2": "stroke:black;stroke-dasharray:2px 2px;",
Y: "font-family:'Open Sans', verdana, arial, sans-serif;position:fixed;top:50px;right:20px;z-index:10000;font-size:10pt;max-width:180px;",
"Y p": "margin:0;",
"Y .notifier-note": "min-width:180px;max-width:250px;border:1px solid #fff;z-index:3000;margin:0;background-color:#8c97af;background-color:rgba(140,151,175,0.9);color:#fff;padding:10px;overflow-wrap:break-word;word-wrap:break-word;-ms-hyphens:auto;-webkit-hyphens:auto;hyphens:auto;",
"Y .notifier-close": "color:#fff;opacity:0.8;float:right;padding:0 5px;background:none;border:none;font-size:20px;font-weight:bold;line-height:20px;",
"Y .notifier-close:hover": "color:#444;text-decoration:none;cursor:pointer;"
};
for(var selector in rules) {
var fullSelector = selector.replace(/^,/,' ,')
.replace(/X/g, '.js-plotly-plot .plotly')
.replace(/Y/g, '.plotly-notifier');
Lib.addStyleRule(fullSelector, rules[selector]);
}
},{"../src/lib":212}],2:[function(_dereq_,module,exports){
/**
* Copyright 2012-2020, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
module.exports = _dereq_('../src/traces/choroplethmapbox');
},{"../src/traces/choroplethmapbox":325}],3:[function(_dereq_,module,exports){
/**
* Copyright 2012-2020, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
module.exports = _dereq_('../src/core');
},{"../src/core":191}],4:[function(_dereq_,module,exports){
/**
* Copyright 2012-2020, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
module.exports = _dereq_('../src/traces/densitymapbox');
},{"../src/traces/densitymapbox":333}],5:[function(_dereq_,module,exports){
/**
* Copyright 2012-2020, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
var Plotly = _dereq_('./core');
Plotly.register([
_dereq_('./scattermapbox'),
_dereq_('./choroplethmapbox'),
_dereq_('./densitymapbox')
]);
module.exports = Plotly;
},{"./choroplethmapbox":2,"./core":3,"./densitymapbox":4,"./scattermapbox":6}],6:[function(_dereq_,module,exports){
/**
* Copyright 2012-2020, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
module.exports = _dereq_('../src/traces/scattermapbox');
},{"../src/traces/scattermapbox":375}],7:[function(_dereq_,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var meta_1 = _dereq_("@turf/meta");
// Note: change RADIUS => earthRadius
var RADIUS = 6378137;
/**
* Takes one or more features and returns their area in square meters.
*
* @name area
* @param {GeoJSON} geojson input GeoJSON feature(s)
* @returns {number} area in square meters
* @example
* var polygon = turf.polygon([[[125, -15], [113, -22], [154, -27], [144, -15], [125, -15]]]);
*
* var area = turf.area(polygon);
*
* //addToMap
* var addToMap = [polygon]
* polygon.properties.area = area
*/
function area(geojson) {
return meta_1.geomReduce(geojson, function (value, geom) {
return value + calculateArea(geom);
}, 0);
}
exports.default = area;
/**
* Calculate Area
*
* @private
* @param {Geometry} geom GeoJSON Geometries
* @returns {number} area
*/
function calculateArea(geom) {
var total = 0;
var i;
switch (geom.type) {
case "Polygon":
return polygonArea(geom.coordinates);
case "MultiPolygon":
for (i = 0; i < geom.coordinates.length; i++) {
total += polygonArea(geom.coordinates[i]);
}
return total;
case "Point":
case "MultiPoint":
case "LineString":
case "MultiLineString":
return 0;
}
return 0;
}
function polygonArea(coords) {
var total = 0;
if (coords && coords.length > 0) {
total += Math.abs(ringArea(coords[0]));
for (var i = 1; i < coords.length; i++) {
total -= Math.abs(ringArea(coords[i]));
}
}
return total;
}
/**
* @private
* Calculate the approximate area of the polygon were it projected onto the earth.
* Note that this area will be positive if ring is oriented clockwise, otherwise it will be negative.
*
* Reference:
* Robert. G. Chamberlain and William H. Duquette, "Some Algorithms for Polygons on a Sphere",
* JPL Publication 07-03, Jet Propulsion
* Laboratory, Pasadena, CA, June 2007 http://trs-new.jpl.nasa.gov/dspace/handle/2014/40409
*
* @param {Array<Array<number>>} coords Ring Coordinates
* @returns {number} The approximate signed geodesic area of the polygon in square meters.
*/
function ringArea(coords) {
var p1;
var p2;
var p3;
var lowerIndex;
var middleIndex;
var upperIndex;
var i;
var total = 0;
var coordsLength = coords.length;
if (coordsLength > 2) {
for (i = 0; i < coordsLength; i++) {
if (i === coordsLength - 2) {
lowerIndex = coordsLength - 2;
middleIndex = coordsLength - 1;
upperIndex = 0;
}
else if (i === coordsLength - 1) {
lowerIndex = coordsLength - 1;
middleIndex = 0;
upperIndex = 1;
}
else {
lowerIndex = i;
middleIndex = i + 1;
upperIndex = i + 2;
}
p1 = coords[lowerIndex];
p2 = coords[middleIndex];
p3 = coords[upperIndex];
total += (rad(p3[0]) - rad(p1[0])) * Math.sin(rad(p2[1]));
}
total = total * RADIUS * RADIUS / 2;
}
return total;
}
function rad(num) {
return num * Math.PI / 180;
}
},{"@turf/meta":11}],8:[function(_dereq_,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var meta_1 = _dereq_("@turf/meta");
/**
* Takes a set of features, calculates the bbox of all input features, and returns a bounding box.
*
* @name bbox
* @param {GeoJSON} geojson any GeoJSON object
* @returns {BBox} bbox extent in [minX, minY, maxX, maxY] order
* @example
* var line = turf.lineString([[-74, 40], [-78, 42], [-82, 35]]);
* var bbox = turf.bbox(line);
* var bboxPolygon = turf.bboxPolygon(bbox);
*
* //addToMap
* var addToMap = [line, bboxPolygon]
*/
function bbox(geojson) {
var result = [Infinity, Infinity, -Infinity, -Infinity];
meta_1.coordEach(geojson, function (coord) {
if (result[0] > coord[0]) {
result[0] = coord[0];
}
if (result[1] > coord[1]) {
result[1] = coord[1];
}
if (result[2] < coord[0]) {
result[2] = coord[0];
}
if (result[3] < coord[1]) {
result[3] = coord[1];
}
});
return result;
}
exports.default = bbox;
},{"@turf/meta":11}],9:[function(_dereq_,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var meta_1 = _dereq_("@turf/meta");
var helpers_1 = _dereq_("@turf/helpers");
/**
* Takes one or more features and calculates the centroid using the mean of all vertices.
* This lessens the effect of small islands and artifacts when calculating the centroid of a set of polygons.
*
* @name centroid
* @param {GeoJSON} geojson GeoJSON to be centered
* @param {Object} [options={}] Optional Parameters
* @param {Object} [options.properties={}] an Object that is used as the {@link Feature}'s properties
* @returns {Feature<Point>} the centroid of the input features
* @example
* var polygon = turf.polygon([[[-81, 41], [-88, 36], [-84, 31], [-80, 33], [-77, 39], [-81, 41]]]);
*
* var centroid = turf.centroid(polygon);
*
* //addToMap
* var addToMap = [polygon, centroid]
*/
function centroid(geojson, options) {
if (options === void 0) { options = {}; }
var xSum = 0;
var ySum = 0;
var len = 0;
meta_1.coordEach(geojson, function (coord) {
xSum += coord[0];
ySum += coord[1];
len++;
});
return helpers_1.point([xSum / len, ySum / len], options.properties);
}
exports.default = centroid;
},{"@turf/helpers":10,"@turf/meta":11}],10:[function(_dereq_,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/**
* @module helpers
*/
/**
* Earth Radius used with the Harvesine formula and approximates using a spherical (non-ellipsoid) Earth.
*
* @memberof helpers
* @type {number}
*/
exports.earthRadius = 6371008.8;
/**
* Unit of measurement factors using a spherical (non-ellipsoid) earth radius.
*
* @memberof helpers
* @type {Object}
*/
exports.factors = {
centimeters: exports.earthRadius * 100,
centimetres: exports.earthRadius * 100,
degrees: exports.earthRadius / 111325,
feet: exports.earthRadius * 3.28084,
inches: exports.earthRadius * 39.370,
kilometers: exports.earthRadius / 1000,
kilometres: exports.earthRadius / 1000,
meters: exports.earthRadius,
metres: exports.earthRadius,
miles: exports.earthRadius / 1609.344,
millimeters: exports.earthRadius * 1000,
millimetres: exports.earthRadius * 1000,
nauticalmiles: exports.earthRadius / 1852,
radians: 1,
yards: exports.earthRadius / 1.0936,
};
/**
* Units of measurement factors based on 1 meter.
*
* @memberof helpers
* @type {Object}
*/
exports.unitsFactors = {
centimeters: 100,
centimetres: 100,
degrees: 1 / 111325,
feet: 3.28084,
inches: 39.370,
kilometers: 1 / 1000,
kilometres: 1 / 1000,
meters: 1,
metres: 1,
miles: 1 / 1609.344,
millimeters: 1000,
millimetres: 1000,
nauticalmiles: 1 / 1852,
radians: 1 / exports.earthRadius,
yards: 1 / 1.0936,
};
/**
* Area of measurement factors based on 1 square meter.
*
* @memberof helpers
* @type {Object}
*/
exports.areaFactors = {
acres: 0.000247105,
centimeters: 10000,
centimetres: 10000,
feet: 10.763910417,
inches: 1550.003100006,
kilometers: 0.000001,
kilometres: 0.000001,
meters: 1,
metres: 1,
miles: 3.86e-7,
millimeters: 1000000,
millimetres: 1000000,
yards: 1.195990046,
};
/**
* Wraps a GeoJSON {@link Geometry} in a GeoJSON {@link Feature}.
*
* @name feature
* @param {Geometry} geometry input geometry
* @param {Object} [properties={}] an Object of key-value pairs to add as properties
* @param {Object} [options={}] Optional Parameters
* @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature
* @param {string|number} [options.id] Identifier associated with the Feature
* @returns {Feature} a GeoJSON Feature
* @example
* var geometry = {
* "type": "Point",
* "coordinates": [110, 50]
* };
*
* var feature = turf.feature(geometry);
*
* //=feature
*/
function feature(geom, properties, options) {
if (options === void 0) { options = {}; }
var feat = { type: "Feature" };
if (options.id === 0 || options.id) {
feat.id = options.id;
}
if (options.bbox) {
feat.bbox = options.bbox;
}
feat.properties = properties || {};
feat.geometry = geom;
return feat;
}
exports.feature = feature;
/**
* Creates a GeoJSON {@link Geometry} from a Geometry string type & coordinates.
* For GeometryCollection type use `helpers.geometryCollection`
*
* @name geometry
* @param {string} type Geometry Type
* @param {Array<any>} coordinates Coordinates
* @param {Object} [options={}] Optional Parameters
* @returns {Geometry} a GeoJSON Geometry
* @example
* var type = "Point";
* var coordinates = [110, 50];
* var geometry = turf.geometry(type, coordinates);
* // => geometry
*/
function geometry(type, coordinates, options) {
if (options === void 0) { options = {}; }
switch (type) {
case "Point": return point(coordinates).geometry;
case "LineString": return lineString(coordinates).geometry;
case "Polygon": return polygon(coordinates).geometry;
case "MultiPoint": return multiPoint(coordinates).geometry;
case "MultiLineString": return multiLineString(coordinates).geometry;
case "MultiPolygon": return multiPolygon(coordinates).geometry;
default: throw new Error(type + " is invalid");
}
}
exports.geometry = geometry;
/**
* Creates a {@link Point} {@link Feature} from a Position.
*
* @name point
* @param {Array<number>} coordinates longitude, latitude position (each in decimal degrees)
* @param {Object} [properties={}] an Object of key-value pairs to add as properties
* @param {Object} [options={}] Optional Parameters
* @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature
* @param {string|number} [options.id] Identifier associated with the Feature
* @returns {Feature<Point>} a Point feature
* @example
* var point = turf.point([-75.343, 39.984]);
*
* //=point
*/
function point(coordinates, properties, options) {
if (options === void 0) { options = {}; }
var geom = {
type: "Point",
coordinates: coordinates,
};
return feature(geom, properties, options);
}
exports.point = point;
/**
* Creates a {@link Point} {@link FeatureCollection} from an Array of Point coordinates.
*
* @name points
* @param {Array<Array<number>>} coordinates an array of Points
* @param {Object} [properties={}] Translate these properties to each Feature
* @param {Object} [options={}] Optional Parameters
* @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north]
* associated with the FeatureCollection
* @param {string|number} [options.id] Identifier associated with the FeatureCollection
* @returns {FeatureCollection<Point>} Point Feature
* @example
* var points = turf.points([
* [-75, 39],
* [-80, 45],
* [-78, 50]
* ]);
*
* //=points
*/
function points(coordinates, properties, options) {
if (options === void 0) { options = {}; }
return featureCollection(coordinates.map(function (coords) {
return point(coords, properties);
}), options);
}
exports.points = points;
/**
* Creates a {@link Polygon} {@link Feature} from an Array of LinearRings.
*
* @name polygon
* @param {Array<Array<Array<number>>>} coordinates an array of LinearRings
* @param {Object} [properties={}] an Object of key-value pairs to add as properties
* @param {Object} [options={}] Optional Parameters
* @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature
* @param {string|number} [options.id] Identifier associated with the Feature
* @returns {Feature<Polygon>} Polygon Feature
* @example
* var polygon = turf.polygon([[[-5, 52], [-4, 56], [-2, 51], [-7, 54], [-5, 52]]], { name: 'poly1' });
*
* //=polygon
*/
function polygon(coordinates, properties, options) {
if (options === void 0) { options = {}; }
for (var _i = 0, coordinates_1 = coordinates; _i < coordinates_1.length; _i++) {
var ring = coordinates_1[_i];
if (ring.length < 4) {
throw new Error("Each LinearRing of a Polygon must have 4 or more Positions.");
}
for (var j = 0; j < ring[ring.length - 1].length; j++) {
// Check if first point of Polygon contains two numbers
if (ring[ring.length - 1][j] !== ring[0][j]) {
throw new Error("First and last Position are not equivalent.");
}
}
}
var geom = {
type: "Polygon",
coordinates: coordinates,
};
return feature(geom, properties, options);
}
exports.polygon = polygon;
/**
* Creates a {@link Polygon} {@link FeatureCollection} from an Array of Polygon coordinates.
*
* @name polygons
* @param {Array<Array<Array<Array<number>>>>} coordinates an array of Polygon coordinates
* @param {Object} [properties={}] an Object of key-value pairs to add as properties
* @param {Object} [options={}] Optional Parameters
* @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature
* @param {string|number} [options.id] Identifier associated with the FeatureCollection
* @returns {FeatureCollection<Polygon>} Polygon FeatureCollection
* @example
* var polygons = turf.polygons([
* [[[-5, 52], [-4, 56], [-2, 51], [-7, 54], [-5, 52]]],
* [[[-15, 42], [-14, 46], [-12, 41], [-17, 44], [-15, 42]]],
* ]);
*
* //=polygons
*/
function polygons(coordinates, properties, options) {
if (options === void 0) { options = {}; }
return featureCollection(coordinates.map(function (coords) {
return polygon(coords, properties);
}), options);
}
exports.polygons = polygons;
/**
* Creates a {@link LineString} {@link Feature} from an Array of Positions.
*
* @name lineString
* @param {Array<Array<number>>} coordinates an array of Positions
* @param {Object} [properties={}] an Object of key-value pairs to add as properties
* @param {Object} [options={}] Optional Parameters
* @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature
* @param {string|number} [options.id] Identifier associated with the Feature
* @returns {Feature<LineString>} LineString Feature
* @example
* var linestring1 = turf.lineString([[-24, 63], [-23, 60], [-25, 65], [-20, 69]], {name: 'line 1'});
* var linestring2 = turf.lineString([[-14, 43], [-13, 40], [-15, 45], [-10, 49]], {name: 'line 2'});
*
* //=linestring1
* //=linestring2
*/
function lineString(coordinates, properties, options) {
if (options === void 0) { options = {}; }
if (coordinates.length < 2) {
throw new Error("coordinates must be an array of two or more positions");
}
var geom = {
type: "LineString",
coordinates: coordinates,
};
return feature(geom, properties, options);
}
exports.lineString = lineString;
/**
* Creates a {@link LineString} {@link FeatureCollection} from an Array of LineString coordinates.
*
* @name lineStrings
* @param {Array<Array<Array<number>>>} coordinates an array of LinearRings
* @param {Object} [properties={}] an Object of key-value pairs to add as properties
* @param {Object} [options={}] Optional Parameters
* @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north]
* associated with the FeatureCollection
* @param {string|number} [options.id] Identifier associated with the FeatureCollection
* @returns {FeatureCollection<LineString>} LineString FeatureCollection
* @example
* var linestrings = turf.lineStrings([
* [[-24, 63], [-23, 60], [-25, 65], [-20, 69]],
* [[-14, 43], [-13, 40], [-15, 45], [-10, 49]]
* ]);
*
* //=linestrings
*/
function lineStrings(coordinates, properties, options) {
if (options === void 0) { options = {}; }
return featureCollection(coordinates.map(function (coords) {
return lineString(coords, properties);
}), options);
}
exports.lineStrings = lineStrings;
/**
* Takes one or more {@link Feature|Features} and creates a {@link FeatureCollection}.
*
* @name featureCollection
* @param {Feature[]} features input features
* @param {Object} [options={}] Optional Parameters
* @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature
* @param {string|number} [options.id] Identifier associated with the Feature
* @returns {FeatureCollection} FeatureCollection of Features
* @example
* var locationA = turf.point([-75.343, 39.984], {name: 'Location A'});
* var locationB = turf.point([-75.833, 39.284], {name: 'Location B'});
* var locationC = turf.point([-75.534, 39.123], {name: 'Location C'});
*
* var collection = turf.featureCollection([
* locationA,
* locationB,
* locationC
* ]);
*
* //=collection
*/
function featureCollection(features, options) {
if (options === void 0) { options = {}; }
var fc = { type: "FeatureCollection" };
if (options.id) {
fc.id = options.id;
}
if (options.bbox) {
fc.bbox = options.bbox;
}
fc.features = features;
return fc;
}
exports.featureCollection = featureCollection;
/**
* Creates a {@link Feature<MultiLineString>} based on a
* coordinate array. Properties can be added optionally.
*
* @name multiLineString
* @param {Array<Array<Array<number>>>} coordinates an array of LineStrings
* @param {Object} [properties={}] an Object of key-value pairs to add as properties
* @param {Object} [options={}] Optional Parameters
* @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature
* @param {string|number} [options.id] Identifier associated with the Feature
* @returns {Feature<MultiLineString>} a MultiLineString feature
* @throws {Error} if no coordinates are passed
* @example
* var multiLine = turf.multiLineString([[[0,0],[10,10]]]);
*
* //=multiLine
*/
function multiLineString(coordinates, properties, options) {
if (options === void 0) { options = {}; }
var geom = {
type: "MultiLineString",
coordinates: coordinates,
};
return feature(geom, properties, options);
}
exports.multiLineString = multiLineString;
/**
* Creates a {@link Feature<MultiPoint>} based on a
* coordinate array. Properties can be added optionally.
*
* @name multiPoint
* @param {Array<Array<number>>} coordinates an array of Positions
* @param {Object} [properties={}] an Object of key-value pairs to add as properties
* @param {Object} [options={}] Optional Parameters
* @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature
* @param {string|number} [options.id] Identifier associated with the Feature
* @returns {Feature<MultiPoint>} a MultiPoint feature
* @throws {Error} if no coordinates are passed
* @example
* var multiPt = turf.multiPoint([[0,0],[10,10]]);
*
* //=multiPt
*/
function multiPoint(coordinates, properties, options) {
if (options === void 0) { options = {}; }
var geom = {
type: "MultiPoint",
coordinates: coordinates,
};
return feature(geom, properties, options);
}
exports.multiPoint = multiPoint;
/**
* Creates a {@link Feature<MultiPolygon>} based on a
* coordinate array. Properties can be added optionally.
*
* @name multiPolygon
* @param {Array<Array<Array<Array<number>>>>} coordinates an array of Polygons
* @param {Object} [properties={}] an Object of key-value pairs to add as properties
* @param {Object} [options={}] Optional Parameters
* @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature
* @param {string|number} [options.id] Identifier associated with the Feature
* @returns {Feature<MultiPolygon>} a multipolygon feature
* @throws {Error} if no coordinates are passed
* @example
* var multiPoly = turf.multiPolygon([[[[0,0],[0,10],[10,10],[10,0],[0,0]]]]);
*
* //=multiPoly
*
*/
function multiPolygon(coordinates, properties, options) {
if (options === void 0) { options = {}; }
var geom = {
type: "MultiPolygon",
coordinates: coordinates,
};
return feature(geom, properties, options);
}
exports.multiPolygon = multiPolygon;
/**
* Creates a {@link Feature<GeometryCollection>} based on a
* coordinate array. Properties can be added optionally.
*
* @name geometryCollection
* @param {Array<Geometry>} geometries an array of GeoJSON Geometries
* @param {Object} [properties={}] an Object of key-value pairs to add as properties
* @param {Object} [options={}] Optional Parameters
* @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature
* @param {string|number} [options.id] Identifier associated with the Feature
* @returns {Feature<GeometryCollection>} a GeoJSON GeometryCollection Feature
* @example
* var pt = turf.geometry("Point", [100, 0]);
* var line = turf.geometry("LineString", [[101, 0], [102, 1]]);
* var collection = turf.geometryCollection([pt, line]);
*
* // => collection
*/
function geometryCollection(geometries, properties, options) {
if (options === void 0) { options = {}; }
var geom = {
type: "GeometryCollection",
geometries: geometries,
};
return feature(geom, properties, options);
}
exports.geometryCollection = geometryCollection;
/**
* Round number to precision
*
* @param {number} num Number
* @param {number} [precision=0] Precision
* @returns {number} rounded number
* @example
* turf.round(120.4321)
* //=120
*
* turf.round(120.4321, 2)
* //=120.43
*/
function round(num, precision) {
if (precision === void 0) { precision = 0; }
if (precision && !(precision >= 0)) {
throw new Error("precision must be a positive number");
}
var multiplier = Math.pow(10, precision || 0);
return Math.round(num * multiplier) / multiplier;
}
exports.round = round;
/**
* Convert a distance measurement (assuming a spherical Earth) from radians to a more friendly unit.
* Valid units: miles, nauticalmiles, inches, yards, meters, metres, kilometers, centimeters, feet
*
* @name radiansToLength
* @param {number} radians in radians across the sphere
* @param {string} [units="kilometers"] can be degrees, radians, miles, or kilometers inches, yards, metres,
* meters, kilometres, kilometers.
* @returns {number} distance
*/
function radiansToLength(radians, units) {
if (units === void 0) { units = "kilometers"; }
var factor = exports.factors[units];
if (!factor) {
throw new Error(units + " units is invalid");
}
return radians * factor;
}
exports.radiansToLength = radiansToLength;
/**
* Convert a distance measurement (assuming a spherical Earth) from a real-world unit into radians
* Valid units: miles, nauticalmiles, inches, yards, meters, metres, kilometers, centimeters, feet
*
* @name lengthToRadians
* @param {number} distance in real units
* @param {string} [units="kilometers"] can be degrees, radians, miles, or kilometers inches, yards, metres,
* meters, kilometres, kilometers.
* @returns {number} radians
*/
function lengthToRadians(distance, units) {
if (units === void 0) { units = "kilometers"; }
var factor = exports.factors[units];
if (!factor) {
throw new Error(units + " units is invalid");
}
return distance / factor;
}
exports.lengthToRadians = lengthToRadians;
/**
* Convert a distance measurement (assuming a spherical Earth) from a real-world unit into degrees
* Valid units: miles, nauticalmiles, inches, yards, meters, metres, centimeters, kilometres, feet
*
* @name lengthToDegrees
* @param {number} distance in real units
* @param {string} [units="kilometers"] can be degrees, radians, miles, or kilometers inches, yards, metres,
* meters, kilometres, kilometers.
* @returns {number} degrees
*/
function lengthToDegrees(distance, units) {
return radiansToDegrees(lengthToRadians(distance, units));
}
exports.lengthToDegrees = lengthToDegrees;
/**
* Converts any bearing angle from the north line direction (positive clockwise)
* and returns an angle between 0-360 degrees (positive clockwise), 0 being the north line
*
* @name bearingToAzimuth
* @param {number} bearing angle, between -180 and +180 degrees
* @returns {number} angle between 0 and 360 degrees
*/
function bearingToAzimuth(bearing) {
var angle = bearing % 360;
if (angle < 0) {
angle += 360;
}
return angle;
}
exports.bearingToAzimuth = bearingToAzimuth;
/**
* Converts an angle in radians to degrees
*
* @name radiansToDegrees
* @param {number} radians angle in radians
* @returns {number} degrees between 0 and 360 degrees
*/
function radiansToDegrees(radians) {
var degrees = radians % (2 * Math.PI);
return degrees * 180 / Math.PI;
}
exports.radiansToDegrees = radiansToDegrees;
/**
* Converts an angle in degrees to radians
*
* @name degreesToRadians
* @param {number} degrees angle between 0 and 360 degrees
* @returns {number} angle in radians
*/
function degreesToRadians(degrees) {
var radians = degrees % 360;
return radians * Math.PI / 180;
}
exports.degreesToRadians = degreesToRadians;
/**
* Converts a length to the requested unit.
* Valid units: miles, nauticalmiles, inches, yards, meters, metres, kilometers, centimeters, feet
*
* @param {number} length to be converted
* @param {Units} [originalUnit="kilometers"] of the length
* @param {Units} [finalUnit="kilometers"] returned unit
* @returns {number} the converted length
*/
function convertLength(length, originalUnit, finalUnit) {
if (originalUnit === void 0) { originalUnit = "kilometers"; }
if (finalUnit === void 0) { finalUnit = "kilometers"; }
if (!(length >= 0)) {
throw new Error("length must be a positive number");
}
return radiansToLength(lengthToRadians(length, originalUnit), finalUnit);
}
exports.convertLength = convertLength;
/**
* Converts a area to the requested unit.
* Valid units: kilometers, kilometres, meters, metres, centimetres, millimeters, acres, miles, yards, feet, inches
* @param {number} area to be converted
* @param {Units} [originalUnit="meters"] of the distance
* @param {Units} [finalUnit="kilometers"] returned unit
* @returns {number} the converted distance
*/
function convertArea(area, originalUnit, finalUnit) {
if (originalUnit === void 0) { originalUnit = "meters"; }
if (finalUnit === void 0) { finalUnit = "kilometers"; }
if (!(area >= 0)) {
throw new Error("area must be a positive number");
}
var startFactor = exports.areaFactors[originalUnit];
if (!startFactor) {
throw new Error("invalid original units");
}
var finalFactor = exports.areaFactors[finalUnit];
if (!finalFactor) {
throw new Error("invalid final units");
}
return (area / startFactor) * finalFactor;
}
exports.convertArea = convertArea;
/**
* isNumber
*
* @param {*} num Number to validate
* @returns {boolean} true/false
* @example
* turf.isNumber(123)
* //=true
* turf.isNumber('foo')
* //=false
*/
function isNumber(num) {
return !isNaN(num) && num !== null && !Array.isArray(num) && !/^\s*$/.test(num);
}
exports.isNumber = isNumber;
/**
* isObject
*
* @param {*} input variable to validate
* @returns {boolean} true/false
* @example
* turf.isObject({elevation: 10})
* //=true
* turf.isObject('foo')
* //=false
*/
function isObject(input) {
return (!!input) && (input.constructor === Object);
}
exports.isObject = isObject;
/**
* Validate BBox
*
* @private
* @param {Array<number>} bbox BBox to validate
* @returns {void}
* @throws Error if BBox is not valid
* @example
* validateBBox([-180, -40, 110, 50])
* //=OK
* validateBBox([-180, -40])
* //=Error
* validateBBox('Foo')
* //=Error
* validateBBox(5)
* //=Error
* validateBBox(null)
* //=Error
* validateBBox(undefined)
* //=Error
*/
function validateBBox(bbox) {
if (!bbox) {
throw new Error("bbox is required");
}
if (!Array.isArray(bbox)) {
throw new Error("bbox must be an Array");
}
if (bbox.length !== 4 && bbox.length !== 6) {
throw new Error("bbox must be an Array of 4 or 6 numbers");
}
bbox.forEach(function (num) {
if (!isNumber(num)) {
throw new Error("bbox must only contain numbers");
}
});
}
exports.validateBBox = validateBBox;
/**
* Validate Id
*
* @private
* @param {string|number} id Id to validate
* @returns {void}
* @throws Error if Id is not valid
* @example
* validateId([-180, -40, 110, 50])
* //=Error
* validateId([-180, -40])
* //=Error
* validateId('Foo')
* //=OK
* validateId(5)
* //=OK
* validateId(null)
* //=Error
* validateId(undefined)
* //=Error
*/
function validateId(id) {
if (!id) {
throw new Error("id is required");
}
if (["string", "number"].indexOf(typeof id) === -1) {
throw new Error("id must be a number or a string");
}
}
exports.validateId = validateId;
// Deprecated methods
function radians2degrees() {
throw new Error("method has been renamed to `radiansToDegrees`");
}
exports.radians2degrees = radians2degrees;
function degrees2radians() {
throw new Error("method has been renamed to `degreesToRadians`");
}
exports.degrees2radians = degrees2radians;
function distanceToDegrees() {
throw new Error("method has been renamed to `lengthToDegrees`");
}
exports.distanceToDegrees = distanceToDegrees;
function distanceToRadians() {
throw new Error("method has been renamed to `lengthToRadians`");
}
exports.distanceToRadians = distanceToRadians;
function radiansToDistance() {
throw new Error("method has been renamed to `radiansToLength`");
}
exports.radiansToDistance = radiansToDistance;
function bearingToAngle() {
throw new Error("method has been renamed to `bearingToAzimuth`");
}
exports.bearingToAngle = bearingToAngle;
function convertDistance() {
throw new Error("method has been renamed to `convertLength`");
}
exports.convertDistance = convertDistance;
},{}],11:[function(_dereq_,module,exports){
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var helpers = _dereq_('@turf/helpers');
/**
* Callback for coordEach
*
* @callback coordEachCallback
* @param {Array<number>} currentCoord The current coordinate being processed.
* @param {number} coordIndex The current index of the coordinate being processed.
* @param {number} featureIndex The current index of the Feature being processed.
* @param {number} multiFeatureIndex The current index of the Multi-Feature being processed.
* @param {number} geometryIndex The current index of the Geometry being processed.
*/
/**
* Iterate over coordinates in any GeoJSON object, similar to Array.forEach()
*
* @name coordEach
* @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON object
* @param {Function} callback a method that takes (currentCoord, coordIndex, featureIndex, multiFeatureIndex)
* @param {boolean} [excludeWrapCoord=false] whether or not to include the final coordinate of LinearRings that wraps the ring in its iteration.
* @returns {void}
* @example
* var features = turf.featureCollection([
* turf.point([26, 37], {"foo": "bar"}),
* turf.point([36, 53], {"hello": "world"})
* ]);
*
* turf.coordEach(features, function (currentCoord, coordIndex, featureIndex, multiFeatureIndex, geometryIndex) {
* //=currentCoord
* //=coordIndex
* //=featureIndex
* //=multiFeatureIndex
* //=geometryIndex
* });
*/
function coordEach(geojson, callback, excludeWrapCoord) {
// Handles null Geometry -- Skips this GeoJSON
if (geojson === null) return;
var j, k, l, geometry, stopG, coords,
geometryMaybeCollection,
wrapShrink = 0,
coordIndex = 0,
isGeometryCollection,
type = geojson.type,
isFeatureCollection = type === 'FeatureCollection',
isFeature = type === 'Feature',
stop = isFeatureCollection ? geojson.features.length : 1;
// This logic may look a little weird. The reason why it is that way
// is because it's trying to be fast. GeoJSON supports multiple kinds
// of objects at its root: FeatureCollection, Features, Geometries.
// This function has the responsibility of handling all of them, and that
// means that some of the `for` loops you see below actually just don't apply
// to certain inputs. For instance, if you give this just a
// Point geometry, then both loops are short-circuited and all we do
// is gradually rename the input until it's called 'geometry'.
//
// This also aims to allocate as few resources as possible: just a
// few numbers and booleans, rather than any temporary arrays as would
// be required with the normalization approach.
for (var featureIndex = 0; featureIndex < stop; featureIndex++) {
geometryMaybeCollection = (isFeatureCollection ? geojson.features[featureIndex].geometry :
(isFeature ? geojson.geometry : geojson));
isGeometryCollection = (geometryMaybeCollection) ? geometryMaybeCollection.type === 'GeometryCollection' : false;
stopG = isGeometryCollection ? geometryMaybeCollection.geometries.length : 1;
for (var geomIndex = 0; geomIndex < stopG; geomIndex++) {
var multiFeatureIndex = 0;
var geometryIndex = 0;
geometry = isGeometryCollection ?
geometryMaybeCollection.geometries[geomIndex] : geometryMaybeCollection;
// Handles null Geometry -- Skips this geometry
if (geometry === null) continue;
coords = geometry.coordinates;
var geomType = geometry.type;
wrapShrink = (excludeWrapCoord && (geomType === 'Polygon' || geomType === 'MultiPolygon')) ? 1 : 0;
switch (geomType) {
case null:
break;
case 'Point':
if (callback(coords, coordIndex, featureIndex, multiFeatureIndex, geometryIndex) === false) return false;
coordIndex++;
multiFeatureIndex++;
break;
case 'LineString':
case 'MultiPoint':
for (j = 0; j < coords.length; j++) {
if (callback(coords[j], coordIndex, featureIndex, multiFeatureIndex, geometryIndex) === false) return false;
coordIndex++;
if (geomType === 'MultiPoint') multiFeatureIndex++;
}
if (geomType === 'LineString') multiFeatureIndex++;
break;
case 'Polygon':
case 'MultiLineString':
for (j = 0; j < coords.length; j++) {
for (k = 0; k < coords[j].length - wrapShrink; k++) {
if (callback(coords[j][k], coordIndex, featureIndex, multiFeatureIndex, geometryIndex) === false) return false;
coordIndex++;
}
if (geomType === 'MultiLineString') multiFeatureIndex++;
if (geomType === 'Polygon') geometryIndex++;
}
if (geomType === 'Polygon') multiFeatureIndex++;
break;
case 'MultiPolygon':
for (j = 0; j < coords.length; j++) {
geometryIndex = 0;
for (k = 0; k < coords[j].length; k++) {
for (l = 0; l < coords[j][k].length - wrapShrink; l++) {
if (callback(coords[j][k][l], coordIndex, featureIndex, multiFeatureIndex, geometryIndex) === false) return false;
coordIndex++;
}
geometryIndex++;
}
multiFeatureIndex++;
}
break;
case 'GeometryCollection':
for (j = 0; j < geometry.geometries.length; j++)
if (coordEach(geometry.geometries[j], callback, excludeWrapCoord) === false) return false;
break;
default:
throw new Error('Unknown Geometry Type');
}
}
}
}
/**
* Callback for coordReduce
*
* The first time the callback function is called, the values provided as arguments depend
* on whether the reduce method has an initialValue argument.
*
* If an initialValue is provided to the reduce method:
* - The previousValue argument is initialValue.
* - The currentValue argument is the value of the first element present in the array.
*
* If an initialValue is not provided:
* - The previousValue argument is the value of the first element present in the array.
* - The currentValue argument is the value of the second element present in the array.
*
* @callback coordReduceCallback
* @param {*} previousValue The accumulated value previously returned in the last invocation
* of the callback, or initialValue, if supplied.
* @param {Array<number>} currentCoord The current coordinate being processed.
* @param {number} coordIndex The current index of the coordinate being processed.
* Starts at index 0, if an initialValue is provided, and at index 1 otherwise.
* @param {number} featureIndex The current index of the Feature being processed.
* @param {number} multiFeatureIndex The current index of the Multi-Feature being processed.
* @param {number} geometryIndex The current index of the Geometry being processed.
*/
/**
* Reduce coordinates in any GeoJSON object, similar to Array.reduce()
*
* @name coordReduce
* @param {FeatureCollection|Geometry|Feature} geojson any GeoJSON object
* @param {Function} callback a method that takes (previousValue, currentCoord, coordIndex)
* @param {*} [initialValue] Value to use as the first argument to the first call of the callback.
* @param {boolean} [excludeWrapCoord=false] whether or not to include the final coordinate of LinearRings that wraps the ring in its iteration.
* @returns {*} The value that results from the reduction.
* @example
* var features = turf.featureCollection([
* turf.point([26, 37], {"foo": "bar"}),
* turf.point([36, 53], {"hello": "world"})
* ]);
*
* turf.coordReduce(features, function (previousValue, currentCoord, coordIndex, featureIndex, multiFeatureIndex, geometryIndex) {
* //=previousValue
* //=currentCoord
* //=coordIndex
* //=featureIndex
* //=multiFeatureIndex
* //=geometryIndex
* return currentCoord;
* });
*/
function coordReduce(geojson, callback, initialValue, excludeWrapCoord) {
var previousValue = initialValue;
coordEach(geojson, function (currentCoord, coordIndex, featureIndex, multiFeatureIndex, geometryIndex) {
if (coordIndex === 0 && initialValue === undefined) previousValue = currentCoord;
else previousValue = callback(previousValue, currentCoord, coordIndex, featureIndex, multiFeatureIndex, geometryIndex);
}, excludeWrapCoord);
return previousValue;
}
/**
* Callback for propEach
*
* @callback propEachCallback
* @param {Object} currentProperties The current Properties being processed.
* @param {number} featureIndex The current index of the Feature being processed.
*/
/**
* Iterate over properties in any GeoJSON object, similar to Array.forEach()
*
* @name propEach
* @param {FeatureCollection|Feature} geojson any GeoJSON object
* @param {Function} callback a method that takes (currentProperties, featureIndex)
* @returns {void}
* @example
* var features = turf.featureCollection([
* turf.point([26, 37], {foo: 'bar'}),
* turf.point([36, 53], {hello: 'world'})
* ]);
*
* turf.propEach(features, function (currentProperties, featureIndex) {
* //=currentProperties
* //=featureIndex
* });
*/
function propEach(geojson, callback) {
var i;
switch (geojson.type) {
case 'FeatureCollection':
for (i = 0; i < geojson.features.length; i++) {
if (callback(geojson.features[i].properties, i) === false) break;
}
break;
case 'Feature':
callback(geojson.properties, 0);
break;
}
}
/**
* Callback for propReduce
*
* The first time the callback function is called, the values provided as arguments depend
* on whether the reduce method has an initialValue argument.
*
* If an initialValue is provided to the reduce method:
* - The previousValue argument is initialValue.
* - The currentValue argument is the value of the first element present in the array.
*
* If an initialValue is not provided:
* - The previousValue argument is the value of the first element present in the array.
* - The currentValue argument is the value of the second element present in the array.
*
* @callback propReduceCallback
* @param {*} previousValue The accumulated value previously returned in the last invocation
* of the callback, or initialValue, if supplied.
* @param {*} currentProperties The current Properties being processed.
* @param {number} featureIndex The current index of the Feature being processed.
*/
/**
* Reduce properties in any GeoJSON object into a single value,
* similar to how Array.reduce works. However, in this case we lazily run
* the reduction, so an array of all properties is unnecessary.
*
* @name propReduce
* @param {FeatureCollection|Featur