/*! * * @supermap/react-iclient.(https://iclient.supermap.io) * Copyright© 2000 - 2023 SuperMap Software Co.Ltd * license: Apache-2.0 * version: v11.1.0 * */ (function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(require("../public/libs/mapboxgl/mapbox-gl-enhance.js"), require("echarts"), require("three/build/three"), require("../public/libs/deckgl/deck.gl.min.js"), require("../public/libs/iclient-mapboxgl/iclient-mapboxgl.min.js"), require("antd"), require("../public/libs/echarts-layer/EchartsLayer.js"), require("react"), require("canvg")); else if(typeof define === 'function' && define.amd) define(["../public/libs/mapboxgl/mapbox-gl-enhance.js", "echarts", "three/build/three", "../public/libs/deckgl/deck.gl.min.js", "../public/libs/iclient-mapboxgl/iclient-mapboxgl.min.js", "antd", "../public/libs/echarts-layer/EchartsLayer.js", "react", "canvg"], factory); else if(typeof exports === 'object') exports["SuperMap"] = factory(require("../public/libs/mapboxgl/mapbox-gl-enhance.js"), require("echarts"), require("three/build/three"), require("../public/libs/deckgl/deck.gl.min.js"), require("../public/libs/iclient-mapboxgl/iclient-mapboxgl.min.js"), require("antd"), require("../public/libs/echarts-layer/EchartsLayer.js"), require("react"), require("canvg")); else root["SuperMap"] = root["SuperMap"] || {}, root["SuperMap"]["Components"] = factory(root["mapboxgl"], root["echarts"], root["THREE"], root["DeckGL"], root["SuperMap"], root["antd"], root["EchartsLayer"], root["React"], root["canvg"]); })(self, function(__WEBPACK_EXTERNAL_MODULE__375__, __WEBPACK_EXTERNAL_MODULE__550__, __WEBPACK_EXTERNAL_MODULE__2069__, __WEBPACK_EXTERNAL_MODULE__2371__, __WEBPACK_EXTERNAL_MODULE__2395__, __WEBPACK_EXTERNAL_MODULE__2721__, __WEBPACK_EXTERNAL_MODULE__3094__, __WEBPACK_EXTERNAL_MODULE__3899__, __WEBPACK_EXTERNAL_MODULE__5973__) { return /******/ (function() { // webpackBootstrap /******/ var __webpack_modules__ = ({ /***/ 9705: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); var meta_1 = __webpack_require__(1540); /** * 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; } bbox["default"] = bbox; exports["default"] = bbox; /***/ }), /***/ 3880: /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) { "use strict"; // ESM COMPAT FLAG __webpack_require__.r(__webpack_exports__); // EXPORTS __webpack_require__.d(__webpack_exports__, { "default": function() { return /* binding */ envelope_main_es; } }); ;// CONCATENATED MODULE: ./node_modules/@turf/envelope/node_modules/@turf/helpers/main.es.js /** * Earth Radius used with the Harvesine formula and approximates using a spherical (non-ellipsoid) Earth. */ var earthRadius = 6371008.8; /** * Unit of measurement factors using a spherical (non-ellipsoid) earth radius. */ var factors = { meters: earthRadius, metres: earthRadius, millimeters: earthRadius * 1000, millimetres: earthRadius * 1000, centimeters: earthRadius * 100, centimetres: earthRadius * 100, kilometers: earthRadius / 1000, kilometres: earthRadius / 1000, miles: earthRadius / 1609.344, nauticalmiles: earthRadius / 1852, inches: earthRadius * 39.370, yards: earthRadius / 1.0936, feet: earthRadius * 3.28084, radians: 1, degrees: earthRadius / 111325, }; /** * Units of measurement factors based on 1 meter. */ var unitsFactors = { meters: 1, metres: 1, millimeters: 1000, millimetres: 1000, centimeters: 100, centimetres: 100, kilometers: 1 / 1000, kilometres: 1 / 1000, miles: 1 / 1609.344, nauticalmiles: 1 / 1852, inches: 39.370, yards: 1 / 1.0936, feet: 3.28084, radians: 1 / earthRadius, degrees: 1 / 111325, }; /** * Area of measurement factors based on 1 square meter. */ var areaFactors = { meters: 1, metres: 1, millimeters: 1000000, millimetres: 1000000, centimeters: 10000, centimetres: 10000, kilometers: 0.000001, kilometres: 0.000001, acres: 0.000247105, miles: 3.86e-7, yards: 1.195990046, feet: 10.763910417, inches: 1550.003100006 }; /** * 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} [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 main_es_feature(geometry, properties, options) { // Optional Parameters options = options || {}; if (!main_es_isObject(options)) throw new Error('options is invalid'); var bbox = options.bbox; var id = options.id; // Validation if (geometry === undefined) throw new Error('geometry is required'); if (properties && properties.constructor !== Object) throw new Error('properties must be an Object'); if (bbox) validateBBox(bbox); if (id) validateId(id); // Main var feat = {type: 'Feature'}; if (id) feat.id = id; if (bbox) feat.bbox = bbox; feat.properties = properties || {}; feat.geometry = geometry; return feat; } /** * 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} coordinates Coordinates * @param {Object} [options={}] Optional Parameters * @param {Array} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Geometry * @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) { // Optional Parameters options = options || {}; if (!main_es_isObject(options)) throw new Error('options is invalid'); var bbox = options.bbox; // Validation if (!type) throw new Error('type is required'); if (!coordinates) throw new Error('coordinates is required'); if (!Array.isArray(coordinates)) throw new Error('coordinates must be an Array'); if (bbox) validateBBox(bbox); // Main var geom; switch (type) { case 'Point': geom = main_es_point(coordinates).geometry; break; case 'LineString': geom = main_es_lineString(coordinates).geometry; break; case 'Polygon': geom = polygon(coordinates).geometry; break; case 'MultiPoint': geom = multiPoint(coordinates).geometry; break; case 'MultiLineString': geom = multiLineString(coordinates).geometry; break; case 'MultiPolygon': geom = multiPolygon(coordinates).geometry; break; default: throw new Error(type + ' is invalid'); } if (bbox) geom.bbox = bbox; return geom; } /** * Creates a {@link Point} {@link Feature} from a Position. * * @name point * @param {Array} 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} [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 Point feature * @example * var point = turf.point([-75.343, 39.984]); * * //=point */ function main_es_point(coordinates, properties, options) { if (!coordinates) throw new Error('coordinates is required'); if (!Array.isArray(coordinates)) throw new Error('coordinates must be an Array'); if (coordinates.length < 2) throw new Error('coordinates must be at least 2 numbers long'); if (!isNumber(coordinates[0]) || !isNumber(coordinates[1])) throw new Error('coordinates must contain numbers'); return main_es_feature({ type: 'Point', coordinates: coordinates }, properties, options); } /** * Creates a {@link Point} {@link FeatureCollection} from an Array of Point coordinates. * * @name points * @param {Array>} coordinates an array of Points * @param {Object} [properties={}] Translate these properties to each Feature * @param {Object} [options={}] Optional Parameters * @param {Array} [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 Feature * @example * var points = turf.points([ * [-75, 39], * [-80, 45], * [-78, 50] * ]); * * //=points */ function points(coordinates, properties, options) { if (!coordinates) throw new Error('coordinates is required'); if (!Array.isArray(coordinates)) throw new Error('coordinates must be an Array'); return featureCollection(coordinates.map(function (coords) { return main_es_point(coords, properties); }), options); } /** * Creates a {@link Polygon} {@link Feature} from an Array of LinearRings. * * @name polygon * @param {Array>>} 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} [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 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 (!coordinates) throw new Error('coordinates is required'); for (var i = 0; i < coordinates.length; i++) { var ring = coordinates[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 (i === 0 && j === 0 && !isNumber(ring[0][0]) || !isNumber(ring[0][1])) throw new Error('coordinates must contain numbers'); if (ring[ring.length - 1][j] !== ring[0][j]) { throw new Error('First and last Position are not equivalent.'); } } } return main_es_feature({ type: 'Polygon', coordinates: coordinates }, properties, options); } /** * Creates a {@link Polygon} {@link FeatureCollection} from an Array of Polygon coordinates. * * @name polygons * @param {Array>>>} 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} [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 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 (!coordinates) throw new Error('coordinates is required'); if (!Array.isArray(coordinates)) throw new Error('coordinates must be an Array'); return featureCollection(coordinates.map(function (coords) { return polygon(coords, properties); }), options); } /** * Creates a {@link LineString} {@link Feature} from an Array of Positions. * * @name lineString * @param {Array>} 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} [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 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 main_es_lineString(coordinates, properties, options) { if (!coordinates) throw new Error('coordinates is required'); if (coordinates.length < 2) throw new Error('coordinates must be an array of two or more positions'); // Check if first point of LineString contains two numbers if (!isNumber(coordinates[0][1]) || !isNumber(coordinates[0][1])) throw new Error('coordinates must contain numbers'); return main_es_feature({ type: 'LineString', coordinates: coordinates }, properties, options); } /** * Creates a {@link LineString} {@link FeatureCollection} from an Array of LineString coordinates. * * @name lineStrings * @param {Array>} 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} [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 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 (!coordinates) throw new Error('coordinates is required'); if (!Array.isArray(coordinates)) throw new Error('coordinates must be an Array'); return featureCollection(coordinates.map(function (coords) { return main_es_lineString(coords, properties); }), options); } /** * 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} [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) { // Optional Parameters options = options || {}; if (!main_es_isObject(options)) throw new Error('options is invalid'); var bbox = options.bbox; var id = options.id; // Validation if (!features) throw new Error('No features passed'); if (!Array.isArray(features)) throw new Error('features must be an Array'); if (bbox) validateBBox(bbox); if (id) validateId(id); // Main var fc = {type: 'FeatureCollection'}; if (id) fc.id = id; if (bbox) fc.bbox = bbox; fc.features = features; return fc; } /** * Creates a {@link Feature} based on a * coordinate array. Properties can be added optionally. * * @name multiLineString * @param {Array>>} 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} [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 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 (!coordinates) throw new Error('coordinates is required'); return main_es_feature({ type: 'MultiLineString', coordinates: coordinates }, properties, options); } /** * Creates a {@link Feature} based on a * coordinate array. Properties can be added optionally. * * @name multiPoint * @param {Array>} 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} [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 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 (!coordinates) throw new Error('coordinates is required'); return main_es_feature({ type: 'MultiPoint', coordinates: coordinates }, properties, options); } /** * Creates a {@link Feature} based on a * coordinate array. Properties can be added optionally. * * @name multiPolygon * @param {Array>>>} 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} [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 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 (!coordinates) throw new Error('coordinates is required'); return main_es_feature({ type: 'MultiPolygon', coordinates: coordinates }, properties, options); } /** * Creates a {@link Feature} based on a * coordinate array. Properties can be added optionally. * * @name geometryCollection * @param {Array} 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} [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 GeometryCollection Feature * @example * var pt = { * "type": "Point", * "coordinates": [100, 0] * }; * var line = { * "type": "LineString", * "coordinates": [ [101, 0], [102, 1] ] * }; * var collection = turf.geometryCollection([pt, line]); * * //=collection */ function geometryCollection(geometries, properties, options) { if (!geometries) throw new Error('geometries is required'); if (!Array.isArray(geometries)) throw new Error('geometries must be an Array'); return main_es_feature({ type: 'GeometryCollection', geometries: geometries }, properties, options); } /** * 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 (num === undefined || num === null || isNaN(num)) throw new Error('num is required'); 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; } /** * 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 (radians === undefined || radians === null) throw new Error('radians is required'); if (units && typeof units !== 'string') throw new Error('units must be a string'); var factor = factors[units || 'kilometers']; if (!factor) throw new Error(units + ' units is invalid'); return radians * factor; } /** * 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 (distance === undefined || distance === null) throw new Error('distance is required'); if (units && typeof units !== 'string') throw new Error('units must be a string'); var factor = factors[units || 'kilometers']; if (!factor) throw new Error(units + ' units is invalid'); return distance / factor; } /** * 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)); } /** * 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) { if (bearing === null || bearing === undefined) throw new Error('bearing is required'); var angle = bearing % 360; if (angle < 0) angle += 360; return angle; } /** * 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) { if (radians === null || radians === undefined) throw new Error('radians is required'); var degrees = radians % (2 * Math.PI); return degrees * 180 / Math.PI; } /** * 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) { if (degrees === null || degrees === undefined) throw new Error('degrees is required'); var radians = degrees % 360; return radians * Math.PI / 180; } /** * 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 {string} originalUnit of the length * @param {string} [finalUnit='kilometers'] returned unit * @returns {number} the converted length */ function convertLength(length, originalUnit, finalUnit) { if (length === null || length === undefined) throw new Error('length is required'); if (!(length >= 0)) throw new Error('length must be a positive number'); return radiansToLength(lengthToRadians(length, originalUnit), finalUnit || 'kilometers'); } /** * 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 {string} [originalUnit='meters'] of the distance * @param {string} [finalUnit='kilometers'] returned unit * @returns {number} the converted distance */ function convertArea(area, originalUnit, finalUnit) { if (area === null || area === undefined) throw new Error('area is required'); if (!(area >= 0)) throw new Error('area must be a positive number'); var startFactor = areaFactors[originalUnit || 'meters']; if (!startFactor) throw new Error('invalid original units'); var finalFactor = areaFactors[finalUnit || 'kilometers']; if (!finalFactor) throw new Error('invalid final units'); return (area / startFactor) * finalFactor; } /** * 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); } /** * isObject * * @param {*} input variable to validate * @returns {boolean} true/false * @example * turf.isObject({elevation: 10}) * //=true * turf.isObject('foo') * //=false */ function main_es_isObject(input) { return (!!input) && (input.constructor === Object); } /** * Validate BBox * * @private * @param {Array} 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'); }); } /** * 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'); } // Deprecated methods function radians2degrees() { throw new Error('method has been renamed to `radiansToDegrees`'); } function degrees2radians() { throw new Error('method has been renamed to `degreesToRadians`'); } function distanceToDegrees() { throw new Error('method has been renamed to `lengthToDegrees`'); } function distanceToRadians() { throw new Error('method has been renamed to `lengthToRadians`'); } function radiansToDistance() { throw new Error('method has been renamed to `radiansToLength`'); } function bearingToAngle() { throw new Error('method has been renamed to `bearingToAzimuth`'); } function convertDistance() { throw new Error('method has been renamed to `convertLength`'); } ;// CONCATENATED MODULE: ./node_modules/@turf/envelope/node_modules/@turf/meta/main.es.js /** * Callback for coordEach * * @callback coordEachCallback * @param {Array} 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++) { if (geomType === 'MultiPolygon') 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} 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|Feature} geojson any GeoJSON object * @param {Function} callback a method that takes (previousValue, currentProperties, featureIndex) * @param {*} [initialValue] Value to use as the first argument to the first call of the callback. * @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.propReduce(features, function (previousValue, currentProperties, featureIndex) { * //=previousValue * //=currentProperties * //=featureIndex * return currentProperties * }); */ function propReduce(geojson, callback, initialValue) { var previousValue = initialValue; propEach(geojson, function (currentProperties, featureIndex) { if (featureIndex === 0 && initialValue === undefined) previousValue = currentProperties; else previousValue = callback(previousValue, currentProperties, featureIndex); }); return previousValue; } /** * Callback for featureEach * * @callback featureEachCallback * @param {Feature} currentFeature The current Feature being processed. * @param {number} featureIndex The current index of the Feature being processed. */ /** * Iterate over features in any GeoJSON object, similar to * Array.forEach. * * @name featureEach * @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON object * @param {Function} callback a method that takes (currentFeature, featureIndex) * @returns {void} * @example * var features = turf.featureCollection([ * turf.point([26, 37], {foo: 'bar'}), * turf.point([36, 53], {hello: 'world'}) * ]); * * turf.featureEach(features, function (currentFeature, featureIndex) { * //=currentFeature * //=featureIndex * }); */ function featureEach(geojson, callback) { if (geojson.type === 'Feature') { callback(geojson, 0); } else if (geojson.type === 'FeatureCollection') { for (var i = 0; i < geojson.features.length; i++) { if (callback(geojson.features[i], i) === false) break; } } } /** * Callback for featureReduce * * 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 featureReduceCallback * @param {*} previousValue The accumulated value previously returned in the last invocation * of the callback, or initialValue, if supplied. * @param {Feature} currentFeature The current Feature being processed. * @param {number} featureIndex The current index of the Feature being processed. */ /** * Reduce features in any GeoJSON object, similar to Array.reduce(). * * @name featureReduce * @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON object * @param {Function} callback a method that takes (previousValue, currentFeature, featureIndex) * @param {*} [initialValue] Value to use as the first argument to the first call of the callback. * @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.featureReduce(features, function (previousValue, currentFeature, featureIndex) { * //=previousValue * //=currentFeature * //=featureIndex * return currentFeature * }); */ function featureReduce(geojson, callback, initialValue) { var previousValue = initialValue; featureEach(geojson, function (currentFeature, featureIndex) { if (featureIndex === 0 && initialValue === undefined) previousValue = currentFeature; else previousValue = callback(previousValue, currentFeature, featureIndex); }); return previousValue; } /** * Get all coordinates from any GeoJSON object. * * @name coordAll * @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON object * @returns {Array>} coordinate position array * @example * var features = turf.featureCollection([ * turf.point([26, 37], {foo: 'bar'}), * turf.point([36, 53], {hello: 'world'}) * ]); * * var coords = turf.coordAll(features); * //= [[26, 37], [36, 53]] */ function coordAll(geojson) { var coords = []; coordEach(geojson, function (coord) { coords.push(coord); }); return coords; } /** * Callback for geomEach * * @callback geomEachCallback * @param {Geometry} currentGeometry The current Geometry being processed. * @param {number} featureIndex The current index of the Feature being processed. * @param {Object} featureProperties The current Feature Properties being processed. * @param {Array} featureBBox The current Feature BBox being processed. * @param {number|string} featureId The current Feature Id being processed. */ /** * Iterate over each geometry in any GeoJSON object, similar to Array.forEach() * * @name geomEach * @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON object * @param {Function} callback a method that takes (currentGeometry, featureIndex, featureProperties, featureBBox, featureId) * @returns {void} * @example * var features = turf.featureCollection([ * turf.point([26, 37], {foo: 'bar'}), * turf.point([36, 53], {hello: 'world'}) * ]); * * turf.geomEach(features, function (currentGeometry, featureIndex, featureProperties, featureBBox, featureId) { * //=currentGeometry * //=featureIndex * //=featureProperties * //=featureBBox * //=featureId * }); */ function geomEach(geojson, callback) { var i, j, g, geometry, stopG, geometryMaybeCollection, isGeometryCollection, featureProperties, featureBBox, featureId, featureIndex = 0, isFeatureCollection = geojson.type === 'FeatureCollection', isFeature = geojson.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 (i = 0; i < stop; i++) { geometryMaybeCollection = (isFeatureCollection ? geojson.features[i].geometry : (isFeature ? geojson.geometry : geojson)); featureProperties = (isFeatureCollection ? geojson.features[i].properties : (isFeature ? geojson.properties : {})); featureBBox = (isFeatureCollection ? geojson.features[i].bbox : (isFeature ? geojson.bbox : undefined)); featureId = (isFeatureCollection ? geojson.features[i].id : (isFeature ? geojson.id : undefined)); isGeometryCollection = (geometryMaybeCollection) ? geometryMaybeCollection.type === 'GeometryCollection' : false; stopG = isGeometryCollection ? geometryMaybeCollection.geometries.length : 1; for (g = 0; g < stopG; g++) { geometry = isGeometryCollection ? geometryMaybeCollection.geometries[g] : geometryMaybeCollection; // Handle null Geometry if (geometry === null) { if (callback(null, featureIndex, featureProperties, featureBBox, featureId) === false) return false; continue; } switch (geometry.type) { case 'Point': case 'LineString': case 'MultiPoint': case 'Polygon': case 'MultiLineString': case 'MultiPolygon': { if (callback(geometry, featureIndex, featureProperties, featureBBox, featureId) === false) return false; break; } case 'GeometryCollection': { for (j = 0; j < geometry.geometries.length; j++) { if (callback(geometry.geometries[j], featureIndex, featureProperties, featureBBox, featureId) === false) return false; } break; } default: throw new Error('Unknown Geometry Type'); } } // Only increase `featureIndex` per each feature featureIndex++; } } /** * Callback for geomReduce * * 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 geomReduceCallback * @param {*} previousValue The accumulated value previously returned in the last invocation * of the callback, or initialValue, if supplied. * @param {Geometry} currentGeometry The current Geometry being processed. * @param {number} featureIndex The current index of the Feature being processed. * @param {Object} featureProperties The current Feature Properties being processed. * @param {Array} featureBBox The current Feature BBox being processed. * @param {number|string} featureId The current Feature Id being processed. */ /** * Reduce geometry in any GeoJSON object, similar to Array.reduce(). * * @name geomReduce * @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON object * @param {Function} callback a method that takes (previousValue, currentGeometry, featureIndex, featureProperties, featureBBox, featureId) * @param {*} [initialValue] Value to use as the first argument to the first call of the callback. * @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.geomReduce(features, function (previousValue, currentGeometry, featureIndex, featureProperties, featureBBox, featureId) { * //=previousValue * //=currentGeometry * //=featureIndex * //=featureProperties * //=featureBBox * //=featureId * return currentGeometry * }); */ function geomReduce(geojson, callback, initialValue) { var previousValue = initialValue; geomEach(geojson, function (currentGeometry, featureIndex, featureProperties, featureBBox, featureId) { if (featureIndex === 0 && initialValue === undefined) previousValue = currentGeometry; else previousValue = callback(previousValue, currentGeometry, featureIndex, featureProperties, featureBBox, featureId); }); return previousValue; } /** * Callback for flattenEach * * @callback flattenEachCallback * @param {Feature} currentFeature The current flattened feature 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. */ /** * Iterate over flattened features in any GeoJSON object, similar to * Array.forEach. * * @name flattenEach * @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON object * @param {Function} callback a method that takes (currentFeature, featureIndex, multiFeatureIndex) * @example * var features = turf.featureCollection([ * turf.point([26, 37], {foo: 'bar'}), * turf.multiPoint([[40, 30], [36, 53]], {hello: 'world'}) * ]); * * turf.flattenEach(features, function (currentFeature, featureIndex, multiFeatureIndex) { * //=currentFeature * //=featureIndex * //=multiFeatureIndex * }); */ function flattenEach(geojson, callback) { geomEach(geojson, function (geometry, featureIndex, properties, bbox, id) { // Callback for single geometry var type = (geometry === null) ? null : geometry.type; switch (type) { case null: case 'Point': case 'LineString': case 'Polygon': if (callback(feature(geometry, properties, {bbox: bbox, id: id}), featureIndex, 0) === false) return false; return; } var geomType; // Callback for multi-geometry switch (type) { case 'MultiPoint': geomType = 'Point'; break; case 'MultiLineString': geomType = 'LineString'; break; case 'MultiPolygon': geomType = 'Polygon'; break; } for (var multiFeatureIndex = 0; multiFeatureIndex < geometry.coordinates.length; multiFeatureIndex++) { var coordinate = geometry.coordinates[multiFeatureIndex]; var geom = { type: geomType, coordinates: coordinate }; if (callback(feature(geom, properties), featureIndex, multiFeatureIndex) === false) return false; } }); } /** * Callback for flattenReduce * * 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 flattenReduceCallback * @param {*} previousValue The accumulated value previously returned in the last invocation * of the callback, or initialValue, if supplied. * @param {Feature} currentFeature The current Feature 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. */ /** * Reduce flattened features in any GeoJSON object, similar to Array.reduce(). * * @name flattenReduce * @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON object * @param {Function} callback a method that takes (previousValue, currentFeature, featureIndex, multiFeatureIndex) * @param {*} [initialValue] Value to use as the first argument to the first call of the callback. * @returns {*} The value that results from the reduction. * @example * var features = turf.featureCollection([ * turf.point([26, 37], {foo: 'bar'}), * turf.multiPoint([[40, 30], [36, 53]], {hello: 'world'}) * ]); * * turf.flattenReduce(features, function (previousValue, currentFeature, featureIndex, multiFeatureIndex) { * //=previousValue * //=currentFeature * //=featureIndex * //=multiFeatureIndex * return currentFeature * }); */ function flattenReduce(geojson, callback, initialValue) { var previousValue = initialValue; flattenEach(geojson, function (currentFeature, featureIndex, multiFeatureIndex) { if (featureIndex === 0 && multiFeatureIndex === 0 && initialValue === undefined) previousValue = currentFeature; else previousValue = callback(previousValue, currentFeature, featureIndex, multiFeatureIndex); }); return previousValue; } /** * Callback for segmentEach * * @callback segmentEachCallback * @param {Feature} currentSegment The current Segment 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. * @param {number} segmentIndex The current index of the Segment being processed. * @returns {void} */ /** * Iterate over 2-vertex line segment in any GeoJSON object, similar to Array.forEach() * (Multi)Point geometries do not contain segments therefore they are ignored during this operation. * * @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON * @param {Function} callback a method that takes (currentSegment, featureIndex, multiFeatureIndex, geometryIndex, segmentIndex) * @returns {void} * @example * var polygon = turf.polygon([[[-50, 5], [-40, -10], [-50, -10], [-40, 5], [-50, 5]]]); * * // Iterate over GeoJSON by 2-vertex segments * turf.segmentEach(polygon, function (currentSegment, featureIndex, multiFeatureIndex, geometryIndex, segmentIndex) { * //=currentSegment * //=featureIndex * //=multiFeatureIndex * //=geometryIndex * //=segmentIndex * }); * * // Calculate the total number of segments * var total = 0; * turf.segmentEach(polygon, function () { * total++; * }); */ function segmentEach(geojson, callback) { flattenEach(geojson, function (feature$$1, featureIndex, multiFeatureIndex) { var segmentIndex = 0; // Exclude null Geometries if (!feature$$1.geometry) return; // (Multi)Point geometries do not contain segments therefore they are ignored during this operation. var type = feature$$1.geometry.type; if (type === 'Point' || type === 'MultiPoint') return; // Generate 2-vertex line segments var previousCoords; if (coordEach(feature$$1, function (currentCoord, coordIndex, featureIndexCoord, mutliPartIndexCoord, geometryIndex) { // Simulating a meta.coordReduce() since `reduce` operations cannot be stopped by returning `false` if (previousCoords === undefined) { previousCoords = currentCoord; return; } var currentSegment = lineString([previousCoords, currentCoord], feature$$1.properties); if (callback(currentSegment, featureIndex, multiFeatureIndex, geometryIndex, segmentIndex) === false) return false; segmentIndex++; previousCoords = currentCoord; }) === false) return false; }); } /** * Callback for segmentReduce * * 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 segmentReduceCallback * @param {*} previousValue The accumulated value previously returned in the last invocation * of the callback, or initialValue, if supplied. * @param {Feature} currentSegment The current Segment 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. * @param {number} segmentIndex The current index of the Segment being processed. */ /** * Reduce 2-vertex line segment in any GeoJSON object, similar to Array.reduce() * (Multi)Point geometries do not contain segments therefore they are ignored during this operation. * * @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON * @param {Function} callback a method that takes (previousValue, currentSegment, currentIndex) * @param {*} [initialValue] Value to use as the first argument to the first call of the callback. * @returns {void} * @example * var polygon = turf.polygon([[[-50, 5], [-40, -10], [-50, -10], [-40, 5], [-50, 5]]]); * * // Iterate over GeoJSON by 2-vertex segments * turf.segmentReduce(polygon, function (previousSegment, currentSegment, featureIndex, multiFeatureIndex, geometryIndex, segmentIndex) { * //= previousSegment * //= currentSegment * //= featureIndex * //= multiFeatureIndex * //= geometryIndex * //= segmentInex * return currentSegment * }); * * // Calculate the total number of segments * var initialValue = 0 * var total = turf.segmentReduce(polygon, function (previousValue) { * previousValue++; * return previousValue; * }, initialValue); */ function segmentReduce(geojson, callback, initialValue) { var previousValue = initialValue; var started = false; segmentEach(geojson, function (currentSegment, featureIndex, multiFeatureIndex, geometryIndex, segmentIndex) { if (started === false && initialValue === undefined) previousValue = currentSegment; else previousValue = callback(previousValue, currentSegment, featureIndex, multiFeatureIndex, geometryIndex, segmentIndex); started = true; }); return previousValue; } /** * Callback for lineEach * * @callback lineEachCallback * @param {Feature} currentLine The current LineString|LinearRing 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 line or ring coordinates in LineString, Polygon, MultiLineString, MultiPolygon Features or Geometries, * similar to Array.forEach. * * @name lineEach * @param {Geometry|Feature} geojson object * @param {Function} callback a method that takes (currentLine, featureIndex, multiFeatureIndex, geometryIndex) * @example * var multiLine = turf.multiLineString([ * [[26, 37], [35, 45]], * [[36, 53], [38, 50], [41, 55]] * ]); * * turf.lineEach(multiLine, function (currentLine, featureIndex, multiFeatureIndex, geometryIndex) { * //=currentLine * //=featureIndex * //=multiFeatureIndex * //=geometryIndex * }); */ function lineEach(geojson, callback) { // validation if (!geojson) throw new Error('geojson is required'); flattenEach(geojson, function (feature$$1, featureIndex, multiFeatureIndex) { if (feature$$1.geometry === null) return; var type = feature$$1.geometry.type; var coords = feature$$1.geometry.coordinates; switch (type) { case 'LineString': if (callback(feature$$1, featureIndex, multiFeatureIndex, 0, 0) === false) return false; break; case 'Polygon': for (var geometryIndex = 0; geometryIndex < coords.length; geometryIndex++) { if (callback(lineString(coords[geometryIndex], feature$$1.properties), featureIndex, multiFeatureIndex, geometryIndex) === false) return false; } break; } }); } /** * Callback for lineReduce * * 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 lineReduceCallback * @param {*} previousValue The accumulated value previously returned in the last invocation * of the callback, or initialValue, if supplied. * @param {Feature} currentLine The current LineString|LinearRing 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 */ /** * Reduce features in any GeoJSON object, similar to Array.reduce(). * * @name lineReduce * @param {Geometry|Feature} geojson object * @param {Function} callback a method that takes (previousValue, currentLine, featureIndex, multiFeatureIndex, geometryIndex) * @param {*} [initialValue] Value to use as the first argument to the first call of the callback. * @returns {*} The value that results from the reduction. * @example * var multiPoly = turf.multiPolygon([ * turf.polygon([[[12,48],[2,41],[24,38],[12,48]], [[9,44],[13,41],[13,45],[9,44]]]), * turf.polygon([[[5, 5], [0, 0], [2, 2], [4, 4], [5, 5]]]) * ]); * * turf.lineReduce(multiPoly, function (previousValue, currentLine, featureIndex, multiFeatureIndex, geometryIndex) { * //=previousValue * //=currentLine * //=featureIndex * //=multiFeatureIndex * //=geometryIndex * return currentLine * }); */ function lineReduce(geojson, callback, initialValue) { var previousValue = initialValue; lineEach(geojson, function (currentLine, featureIndex, multiFeatureIndex, geometryIndex) { if (featureIndex === 0 && initialValue === undefined) previousValue = currentLine; else previousValue = callback(previousValue, currentLine, featureIndex, multiFeatureIndex, geometryIndex); }); return previousValue; } /** * Finds a particular 2-vertex LineString Segment from a GeoJSON using `@turf/meta` indexes. * * Negative indexes are permitted. * Point & MultiPoint will always return null. * * @param {FeatureCollection|Feature|Geometry} geojson Any GeoJSON Feature or Geometry * @param {Object} [options={}] Optional parameters * @param {number} [options.featureIndex=0] Feature Index * @param {number} [options.multiFeatureIndex=0] Multi-Feature Index * @param {number} [options.geometryIndex=0] Geometry Index * @param {number} [options.segmentIndex=0] Segment Index * @param {Object} [options.properties={}] Translate Properties to output LineString * @param {BBox} [options.bbox={}] Translate BBox to output LineString * @param {number|string} [options.id={}] Translate Id to output LineString * @returns {Feature} 2-vertex GeoJSON Feature LineString * @example * var multiLine = turf.multiLineString([ * [[10, 10], [50, 30], [30, 40]], * [[-10, -10], [-50, -30], [-30, -40]] * ]); * * // First Segment (defaults are 0) * turf.findSegment(multiLine); * // => Feature> * * // First Segment of 2nd Multi Feature * turf.findSegment(multiLine, {multiFeatureIndex: 1}); * // => Feature> * * // Last Segment of Last Multi Feature * turf.findSegment(multiLine, {multiFeatureIndex: -1, segmentIndex: -1}); * // => Feature> */ function findSegment(geojson, options) { // Optional Parameters options = options || {}; if (!isObject(options)) throw new Error('options is invalid'); var featureIndex = options.featureIndex || 0; var multiFeatureIndex = options.multiFeatureIndex || 0; var geometryIndex = options.geometryIndex || 0; var segmentIndex = options.segmentIndex || 0; // Find FeatureIndex var properties = options.properties; var geometry; switch (geojson.type) { case 'FeatureCollection': if (featureIndex < 0) featureIndex = geojson.features.length + featureIndex; properties = properties || geojson.features[featureIndex].properties; geometry = geojson.features[featureIndex].geometry; break; case 'Feature': properties = properties || geojson.properties; geometry = geojson.geometry; break; case 'Point': case 'MultiPoint': return null; case 'LineString': case 'Polygon': case 'MultiLineString': case 'MultiPolygon': geometry = geojson; break; default: throw new Error('geojson is invalid'); } // Find SegmentIndex if (geometry === null) return null; var coords = geometry.coordinates; switch (geometry.type) { case 'Point': case 'MultiPoint': return null; case 'LineString': if (segmentIndex < 0) segmentIndex = coords.length + segmentIndex - 1; return lineString([coords[segmentIndex], coords[segmentIndex + 1]], properties, options); case 'Polygon': if (geometryIndex < 0) geometryIndex = coords.length + geometryIndex; if (segmentIndex < 0) segmentIndex = coords[geometryIndex].length + segmentIndex - 1; return lineString([coords[geometryIndex][segmentIndex], coords[geometryIndex][segmentIndex + 1]], properties, options); case 'MultiLineString': if (multiFeatureIndex < 0) multiFeatureIndex = coords.length + multiFeatureIndex; if (segmentIndex < 0) segmentIndex = coords[multiFeatureIndex].length + segmentIndex - 1; return lineString([coords[multiFeatureIndex][segmentIndex], coords[multiFeatureIndex][segmentIndex + 1]], properties, options); case 'MultiPolygon': if (multiFeatureIndex < 0) multiFeatureIndex = coords.length + multiFeatureIndex; if (geometryIndex < 0) geometryIndex = coords[multiFeatureIndex].length + geometryIndex; if (segmentIndex < 0) segmentIndex = coords[multiFeatureIndex][geometryIndex].length - segmentIndex - 1; return lineString([coords[multiFeatureIndex][geometryIndex][segmentIndex], coords[multiFeatureIndex][geometryIndex][segmentIndex + 1]], properties, options); } throw new Error('geojson is invalid'); } /** * Finds a particular Point from a GeoJSON using `@turf/meta` indexes. * * Negative indexes are permitted. * * @param {FeatureCollection|Feature|Geometry} geojson Any GeoJSON Feature or Geometry * @param {Object} [options={}] Optional parameters * @param {number} [options.featureIndex=0] Feature Index * @param {number} [options.multiFeatureIndex=0] Multi-Feature Index * @param {number} [options.geometryIndex=0] Geometry Index * @param {number} [options.coordIndex=0] Coord Index * @param {Object} [options.properties={}] Translate Properties to output Point * @param {BBox} [options.bbox={}] Translate BBox to output Point * @param {number|string} [options.id={}] Translate Id to output Point * @returns {Feature} 2-vertex GeoJSON Feature Point * @example * var multiLine = turf.multiLineString([ * [[10, 10], [50, 30], [30, 40]], * [[-10, -10], [-50, -30], [-30, -40]] * ]); * * // First Segment (defaults are 0) * turf.findPoint(multiLine); * // => Feature> * * // First Segment of the 2nd Multi-Feature * turf.findPoint(multiLine, {multiFeatureIndex: 1}); * // => Feature> * * // Last Segment of last Multi-Feature * turf.findPoint(multiLine, {multiFeatureIndex: -1, coordIndex: -1}); * // => Feature> */ function findPoint(geojson, options) { // Optional Parameters options = options || {}; if (!isObject(options)) throw new Error('options is invalid'); var featureIndex = options.featureIndex || 0; var multiFeatureIndex = options.multiFeatureIndex || 0; var geometryIndex = options.geometryIndex || 0; var coordIndex = options.coordIndex || 0; // Find FeatureIndex var properties = options.properties; var geometry; switch (geojson.type) { case 'FeatureCollection': if (featureIndex < 0) featureIndex = geojson.features.length + featureIndex; properties = properties || geojson.features[featureIndex].properties; geometry = geojson.features[featureIndex].geometry; break; case 'Feature': properties = properties || geojson.properties; geometry = geojson.geometry; break; case 'Point': case 'MultiPoint': return null; case 'LineString': case 'Polygon': case 'MultiLineString': case 'MultiPolygon': geometry = geojson; break; default: throw new Error('geojson is invalid'); } // Find Coord Index if (geometry === null) return null; var coords = geometry.coordinates; switch (geometry.type) { case 'Point': return point(coords, properties, options); case 'MultiPoint': if (multiFeatureIndex < 0) multiFeatureIndex = coords.length + multiFeatureIndex; return point(coords[multiFeatureIndex], properties, options); case 'LineString': if (coordIndex < 0) coordIndex = coords.length + coordIndex; return point(coords[coordIndex], properties, options); case 'Polygon': if (geometryIndex < 0) geometryIndex = coords.length + geometryIndex; if (coordIndex < 0) coordIndex = coords[geometryIndex].length + coordIndex; return point(coords[geometryIndex][coordIndex], properties, options); case 'MultiLineString': if (multiFeatureIndex < 0) multiFeatureIndex = coords.length + multiFeatureIndex; if (coordIndex < 0) coordIndex = coords[multiFeatureIndex].length + coordIndex; return point(coords[multiFeatureIndex][coordIndex], properties, options); case 'MultiPolygon': if (multiFeatureIndex < 0) multiFeatureIndex = coords.length + multiFeatureIndex; if (geometryIndex < 0) geometryIndex = coords[multiFeatureIndex].length + geometryIndex; if (coordIndex < 0) coordIndex = coords[multiFeatureIndex][geometryIndex].length - coordIndex; return point(coords[multiFeatureIndex][geometryIndex][coordIndex], properties, options); } throw new Error('geojson is invalid'); } ;// CONCATENATED MODULE: ./node_modules/@turf/envelope/node_modules/@turf/bbox/main.es.js /** * 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 BBox = [Infinity, Infinity, -Infinity, -Infinity]; coordEach(geojson, function (coord) { if (BBox[0] > coord[0]) BBox[0] = coord[0]; if (BBox[1] > coord[1]) BBox[1] = coord[1]; if (BBox[2] < coord[0]) BBox[2] = coord[0]; if (BBox[3] < coord[1]) BBox[3] = coord[1]; }); return BBox; } /* harmony default export */ var main_es = (bbox); ;// CONCATENATED MODULE: ./node_modules/@turf/bbox-polygon/node_modules/@turf/helpers/main.es.js /** * Earth Radius used with the Harvesine formula and approximates using a spherical (non-ellipsoid) Earth. */ var main_es_earthRadius = 6371008.8; /** * Unit of measurement factors using a spherical (non-ellipsoid) earth radius. */ var main_es_factors = { meters: main_es_earthRadius, metres: main_es_earthRadius, millimeters: main_es_earthRadius * 1000, millimetres: main_es_earthRadius * 1000, centimeters: main_es_earthRadius * 100, centimetres: main_es_earthRadius * 100, kilometers: main_es_earthRadius / 1000, kilometres: main_es_earthRadius / 1000, miles: main_es_earthRadius / 1609.344, nauticalmiles: main_es_earthRadius / 1852, inches: main_es_earthRadius * 39.370, yards: main_es_earthRadius / 1.0936, feet: main_es_earthRadius * 3.28084, radians: 1, degrees: main_es_earthRadius / 111325, }; /** * Units of measurement factors based on 1 meter. */ var main_es_unitsFactors = { meters: 1, metres: 1, millimeters: 1000, millimetres: 1000, centimeters: 100, centimetres: 100, kilometers: 1 / 1000, kilometres: 1 / 1000, miles: 1 / 1609.344, nauticalmiles: 1 / 1852, inches: 39.370, yards: 1 / 1.0936, feet: 3.28084, radians: 1 / main_es_earthRadius, degrees: 1 / 111325, }; /** * Area of measurement factors based on 1 square meter. */ var main_es_areaFactors = { meters: 1, metres: 1, millimeters: 1000000, millimetres: 1000000, centimeters: 10000, centimetres: 10000, kilometers: 0.000001, kilometres: 0.000001, acres: 0.000247105, miles: 3.86e-7, yards: 1.195990046, feet: 10.763910417, inches: 1550.003100006 }; /** * 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} [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 helpers_main_es_feature(geometry, properties, options) { // Optional Parameters options = options || {}; if (!helpers_main_es_isObject(options)) throw new Error('options is invalid'); var bbox = options.bbox; var id = options.id; // Validation if (geometry === undefined) throw new Error('geometry is required'); if (properties && properties.constructor !== Object) throw new Error('properties must be an Object'); if (bbox) main_es_validateBBox(bbox); if (id) main_es_validateId(id); // Main var feat = {type: 'Feature'}; if (id) feat.id = id; if (bbox) feat.bbox = bbox; feat.properties = properties || {}; feat.geometry = geometry; return feat; } /** * 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} coordinates Coordinates * @param {Object} [options={}] Optional Parameters * @param {Array} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Geometry * @returns {Geometry} a GeoJSON Geometry * @example * var type = 'Point'; * var coordinates = [110, 50]; * * var geometry = turf.geometry(type, coordinates); * * //=geometry */ function main_es_geometry(type, coordinates, options) { // Optional Parameters options = options || {}; if (!helpers_main_es_isObject(options)) throw new Error('options is invalid'); var bbox = options.bbox; // Validation if (!type) throw new Error('type is required'); if (!coordinates) throw new Error('coordinates is required'); if (!Array.isArray(coordinates)) throw new Error('coordinates must be an Array'); if (bbox) main_es_validateBBox(bbox); // Main var geom; switch (type) { case 'Point': geom = helpers_main_es_point(coordinates).geometry; break; case 'LineString': geom = helpers_main_es_lineString(coordinates).geometry; break; case 'Polygon': geom = main_es_polygon(coordinates).geometry; break; case 'MultiPoint': geom = main_es_multiPoint(coordinates).geometry; break; case 'MultiLineString': geom = main_es_multiLineString(coordinates).geometry; break; case 'MultiPolygon': geom = main_es_multiPolygon(coordinates).geometry; break; default: throw new Error(type + ' is invalid'); } if (bbox) geom.bbox = bbox; return geom; } /** * Creates a {@link Point} {@link Feature} from a Position. * * @name point * @param {Array} 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} [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 Point feature * @example * var point = turf.point([-75.343, 39.984]); * * //=point */ function helpers_main_es_point(coordinates, properties, options) { if (!coordinates) throw new Error('coordinates is required'); if (!Array.isArray(coordinates)) throw new Error('coordinates must be an Array'); if (coordinates.length < 2) throw new Error('coordinates must be at least 2 numbers long'); if (!main_es_isNumber(coordinates[0]) || !main_es_isNumber(coordinates[1])) throw new Error('coordinates must contain numbers'); return helpers_main_es_feature({ type: 'Point', coordinates: coordinates }, properties, options); } /** * Creates a {@link Point} {@link FeatureCollection} from an Array of Point coordinates. * * @name points * @param {Array>} coordinates an array of Points * @param {Object} [properties={}] Translate these properties to each Feature * @param {Object} [options={}] Optional Parameters * @param {Array} [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 Feature * @example * var points = turf.points([ * [-75, 39], * [-80, 45], * [-78, 50] * ]); * * //=points */ function main_es_points(coordinates, properties, options) { if (!coordinates) throw new Error('coordinates is required'); if (!Array.isArray(coordinates)) throw new Error('coordinates must be an Array'); return main_es_featureCollection(coordinates.map(function (coords) { return helpers_main_es_point(coords, properties); }), options); } /** * Creates a {@link Polygon} {@link Feature} from an Array of LinearRings. * * @name polygon * @param {Array>>} 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} [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 Feature * @example * var polygon = turf.polygon([[[-5, 52], [-4, 56], [-2, 51], [-7, 54], [-5, 52]]], { name: 'poly1' }); * * //=polygon */ function main_es_polygon(coordinates, properties, options) { if (!coordinates) throw new Error('coordinates is required'); for (var i = 0; i < coordinates.length; i++) { var ring = coordinates[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 (i === 0 && j === 0 && !main_es_isNumber(ring[0][0]) || !main_es_isNumber(ring[0][1])) throw new Error('coordinates must contain numbers'); if (ring[ring.length - 1][j] !== ring[0][j]) { throw new Error('First and last Position are not equivalent.'); } } } return helpers_main_es_feature({ type: 'Polygon', coordinates: coordinates }, properties, options); } /** * Creates a {@link Polygon} {@link FeatureCollection} from an Array of Polygon coordinates. * * @name polygons * @param {Array>>>} 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} [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 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 main_es_polygons(coordinates, properties, options) { if (!coordinates) throw new Error('coordinates is required'); if (!Array.isArray(coordinates)) throw new Error('coordinates must be an Array'); return main_es_featureCollection(coordinates.map(function (coords) { return main_es_polygon(coords, properties); }), options); } /** * Creates a {@link LineString} {@link Feature} from an Array of Positions. * * @name lineString * @param {Array>} 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} [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 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 helpers_main_es_lineString(coordinates, properties, options) { if (!coordinates) throw new Error('coordinates is required'); if (coordinates.length < 2) throw new Error('coordinates must be an array of two or more positions'); // Check if first point of LineString contains two numbers if (!main_es_isNumber(coordinates[0][1]) || !main_es_isNumber(coordinates[0][1])) throw new Error('coordinates must contain numbers'); return helpers_main_es_feature({ type: 'LineString', coordinates: coordinates }, properties, options); } /** * Creates a {@link LineString} {@link FeatureCollection} from an Array of LineString coordinates. * * @name lineStrings * @param {Array>} 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} [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 FeatureCollection * @example * var linestrings = turf.lineStrings([ * [[-24, 63], [-23, 60], [-25, 65], [-20, 69]], * [[-14, 43], [-13, 40], [-15, 45], [-10, 49]] * ]); * * //=linestrings */ function main_es_lineStrings(coordinates, properties, options) { if (!coordinates) throw new Error('coordinates is required'); if (!Array.isArray(coordinates)) throw new Error('coordinates must be an Array'); return main_es_featureCollection(coordinates.map(function (coords) { return helpers_main_es_lineString(coords, properties); }), options); } /** * 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} [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 main_es_featureCollection(features, options) { // Optional Parameters options = options || {}; if (!helpers_main_es_isObject(options)) throw new Error('options is invalid'); var bbox = options.bbox; var id = options.id; // Validation if (!features) throw new Error('No features passed'); if (!Array.isArray(features)) throw new Error('features must be an Array'); if (bbox) main_es_validateBBox(bbox); if (id) main_es_validateId(id); // Main var fc = {type: 'FeatureCollection'}; if (id) fc.id = id; if (bbox) fc.bbox = bbox; fc.features = features; return fc; } /** * Creates a {@link Feature} based on a * coordinate array. Properties can be added optionally. * * @name multiLineString * @param {Array>>} 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} [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 MultiLineString feature * @throws {Error} if no coordinates are passed * @example * var multiLine = turf.multiLineString([[[0,0],[10,10]]]); * * //=multiLine */ function main_es_multiLineString(coordinates, properties, options) { if (!coordinates) throw new Error('coordinates is required'); return helpers_main_es_feature({ type: 'MultiLineString', coordinates: coordinates }, properties, options); } /** * Creates a {@link Feature} based on a * coordinate array. Properties can be added optionally. * * @name multiPoint * @param {Array>} 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} [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 MultiPoint feature * @throws {Error} if no coordinates are passed * @example * var multiPt = turf.multiPoint([[0,0],[10,10]]); * * //=multiPt */ function main_es_multiPoint(coordinates, properties, options) { if (!coordinates) throw new Error('coordinates is required'); return helpers_main_es_feature({ type: 'MultiPoint', coordinates: coordinates }, properties, options); } /** * Creates a {@link Feature} based on a * coordinate array. Properties can be added optionally. * * @name multiPolygon * @param {Array>>>} 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} [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 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 main_es_multiPolygon(coordinates, properties, options) { if (!coordinates) throw new Error('coordinates is required'); return helpers_main_es_feature({ type: 'MultiPolygon', coordinates: coordinates }, properties, options); } /** * Creates a {@link Feature} based on a * coordinate array. Properties can be added optionally. * * @name geometryCollection * @param {Array} 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} [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 GeometryCollection Feature * @example * var pt = { * "type": "Point", * "coordinates": [100, 0] * }; * var line = { * "type": "LineString", * "coordinates": [ [101, 0], [102, 1] ] * }; * var collection = turf.geometryCollection([pt, line]); * * //=collection */ function main_es_geometryCollection(geometries, properties, options) { if (!geometries) throw new Error('geometries is required'); if (!Array.isArray(geometries)) throw new Error('geometries must be an Array'); return helpers_main_es_feature({ type: 'GeometryCollection', geometries: geometries }, properties, options); } /** * 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 main_es_round(num, precision) { if (num === undefined || num === null || isNaN(num)) throw new Error('num is required'); 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; } /** * 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 main_es_radiansToLength(radians, units) { if (radians === undefined || radians === null) throw new Error('radians is required'); if (units && typeof units !== 'string') throw new Error('units must be a string'); var factor = main_es_factors[units || 'kilometers']; if (!factor) throw new Error(units + ' units is invalid'); return radians * factor; } /** * 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 main_es_lengthToRadians(distance, units) { if (distance === undefined || distance === null) throw new Error('distance is required'); if (units && typeof units !== 'string') throw new Error('units must be a string'); var factor = main_es_factors[units || 'kilometers']; if (!factor) throw new Error(units + ' units is invalid'); return distance / factor; } /** * 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 main_es_lengthToDegrees(distance, units) { return main_es_radiansToDegrees(main_es_lengthToRadians(distance, units)); } /** * 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 main_es_bearingToAzimuth(bearing) { if (bearing === null || bearing === undefined) throw new Error('bearing is required'); var angle = bearing % 360; if (angle < 0) angle += 360; return angle; } /** * Converts an angle in radians to degrees * * @name radiansToDegrees * @param {number} radians angle in radians * @returns {number} degrees between 0 and 360 degrees */ function main_es_radiansToDegrees(radians) { if (radians === null || radians === undefined) throw new Error('radians is required'); var degrees = radians % (2 * Math.PI); return degrees * 180 / Math.PI; } /** * Converts an angle in degrees to radians * * @name degreesToRadians * @param {number} degrees angle between 0 and 360 degrees * @returns {number} angle in radians */ function main_es_degreesToRadians(degrees) { if (degrees === null || degrees === undefined) throw new Error('degrees is required'); var radians = degrees % 360; return radians * Math.PI / 180; } /** * 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 {string} originalUnit of the length * @param {string} [finalUnit='kilometers'] returned unit * @returns {number} the converted length */ function main_es_convertLength(length, originalUnit, finalUnit) { if (length === null || length === undefined) throw new Error('length is required'); if (!(length >= 0)) throw new Error('length must be a positive number'); return main_es_radiansToLength(main_es_lengthToRadians(length, originalUnit), finalUnit || 'kilometers'); } /** * 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 {string} [originalUnit='meters'] of the distance * @param {string} [finalUnit='kilometers'] returned unit * @returns {number} the converted distance */ function main_es_convertArea(area, originalUnit, finalUnit) { if (area === null || area === undefined) throw new Error('area is required'); if (!(area >= 0)) throw new Error('area must be a positive number'); var startFactor = main_es_areaFactors[originalUnit || 'meters']; if (!startFactor) throw new Error('invalid original units'); var finalFactor = main_es_areaFactors[finalUnit || 'kilometers']; if (!finalFactor) throw new Error('invalid final units'); return (area / startFactor) * finalFactor; } /** * isNumber * * @param {*} num Number to validate * @returns {boolean} true/false * @example * turf.isNumber(123) * //=true * turf.isNumber('foo') * //=false */ function main_es_isNumber(num) { return !isNaN(num) && num !== null && !Array.isArray(num); } /** * isObject * * @param {*} input variable to validate * @returns {boolean} true/false * @example * turf.isObject({elevation: 10}) * //=true * turf.isObject('foo') * //=false */ function helpers_main_es_isObject(input) { return (!!input) && (input.constructor === Object); } /** * Validate BBox * * @private * @param {Array} 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 main_es_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 (!main_es_isNumber(num)) throw new Error('bbox must only contain numbers'); }); } /** * 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 main_es_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'); } // Deprecated methods function main_es_radians2degrees() { throw new Error('method has been renamed to `radiansToDegrees`'); } function main_es_degrees2radians() { throw new Error('method has been renamed to `degreesToRadians`'); } function main_es_distanceToDegrees() { throw new Error('method has been renamed to `lengthToDegrees`'); } function main_es_distanceToRadians() { throw new Error('method has been renamed to `lengthToRadians`'); } function main_es_radiansToDistance() { throw new Error('method has been renamed to `radiansToLength`'); } function main_es_bearingToAngle() { throw new Error('method has been renamed to `bearingToAzimuth`'); } function main_es_convertDistance() { throw new Error('method has been renamed to `convertLength`'); } ;// CONCATENATED MODULE: ./node_modules/@turf/bbox-polygon/main.es.js /** * Takes a bbox and returns an equivalent {@link Polygon|polygon}. * * @name bboxPolygon * @param {BBox} bbox extent in [minX, minY, maxX, maxY] order * @returns {Feature} a Polygon representation of the bounding box * @example * var bbox = [0, 0, 10, 10]; * * var poly = turf.bboxPolygon(bbox); * * //addToMap * var addToMap = [poly] */ function bboxPolygon(bbox) { main_es_validateBBox(bbox); // Convert BBox positions to Numbers // No performance loss for including Number() // https://github.com/Turfjs/turf/issues/1119 var west = Number(bbox[0]); var south = Number(bbox[1]); var east = Number(bbox[2]); var north = Number(bbox[3]); if (bbox.length === 6) throw new Error('@turf/bbox-polygon does not support BBox with 6 positions'); var lowLeft = [west, south]; var topLeft = [west, north]; var topRight = [east, north]; var lowRight = [east, south]; return main_es_polygon([[ lowLeft, lowRight, topRight, topLeft, lowLeft ]]); } /* harmony default export */ var bbox_polygon_main_es = (bboxPolygon); ;// CONCATENATED MODULE: ./node_modules/@turf/envelope/main.es.js /** * Takes any number of features and returns a rectangular {@link Polygon} that encompasses all vertices. * * @name envelope * @param {GeoJSON} geojson input features * @returns {Feature} a rectangular Polygon feature that encompasses all vertices * @example * var features = turf.featureCollection([ * turf.point([-75.343, 39.984], {"name": "Location A"}), * turf.point([-75.833, 39.284], {"name": "Location B"}), * turf.point([-75.534, 39.123], {"name": "Location C"}) * ]); * * var enveloped = turf.envelope(features); * * //addToMap * var addToMap = [features, enveloped]; */ function envelope(geojson) { return bbox_polygon_main_es(main_es(geojson)); } /* harmony default export */ var envelope_main_es = (envelope); /***/ }), /***/ 4102: /***/ (function(__unused_webpack_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.37, 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.37, 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.0936133, }; /** * 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, hectares: 0.0001, 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} [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} 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} 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} [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 Point feature * @example * var point = turf.point([-75.343, 39.984]); * * //=point */ function point(coordinates, properties, options) { if (options === void 0) { options = {}; } if (!coordinates) { throw new Error("coordinates is required"); } if (!Array.isArray(coordinates)) { throw new Error("coordinates must be an Array"); } if (coordinates.length < 2) { throw new Error("coordinates must be at least 2 numbers long"); } if (!isNumber(coordinates[0]) || !isNumber(coordinates[1])) { throw new Error("coordinates must contain numbers"); } 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>} coordinates an array of Points * @param {Object} [properties={}] Translate these properties to each Feature * @param {Object} [options={}] Optional Parameters * @param {Array} [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 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>>} 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} [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 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>>>} 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} [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 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>} 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} [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 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>>} 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} [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 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} [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} based on a * coordinate array. Properties can be added optionally. * * @name multiLineString * @param {Array>>} 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} [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 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} based on a * coordinate array. Properties can be added optionally. * * @name multiPoint * @param {Array>} 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} [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 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} based on a * coordinate array. Properties can be added optionally. * * @name multiPolygon * @param {Array>>>} 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} [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 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} based on a * coordinate array. Properties can be added optionally. * * @name geometryCollection * @param {Array} 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} [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 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, 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, 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, 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, hectares * @param {number} area to be converted * @param {Units} [originalUnit="meters"] of the distance * @param {Units} [finalUnit="kilometers"] returned unit * @returns {number} the converted area */ 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); } 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} 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; /***/ }), /***/ 1540: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); var helpers = __webpack_require__(4102); /** * Callback for coordEach * * @callback coordEachCallback * @param {Array} 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} 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|Feature} geojson any GeoJSON object * @param {Function} callback a method that takes (previousValue, currentProperties, featureIndex) * @param {*} [initialValue] Value to use as the first argument to the first call of the callback. * @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.propReduce(features, function (previousValue, currentProperties, featureIndex) { * //=previousValue * //=currentProperties * //=featureIndex * return currentProperties * }); */ function propReduce(geojson, callback, initialValue) { var previousValue = initialValue; propEach(geojson, function (currentProperties, featureIndex) { if (featureIndex === 0 && initialValue === undefined) previousValue = currentProperties; else previousValue = callback(previousValue, currentProperties, featureIndex); }); return previousValue; } /** * Callback for featureEach * * @callback featureEachCallback * @param {Feature} currentFeature The current Feature being processed. * @param {number} featureIndex The current index of the Feature being processed. */ /** * Iterate over features in any GeoJSON object, similar to * Array.forEach. * * @name featureEach * @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON object * @param {Function} callback a method that takes (currentFeature, featureIndex) * @returns {void} * @example * var features = turf.featureCollection([ * turf.point([26, 37], {foo: 'bar'}), * turf.point([36, 53], {hello: 'world'}) * ]); * * turf.featureEach(features, function (currentFeature, featureIndex) { * //=currentFeature * //=featureIndex * }); */ function featureEach(geojson, callback) { if (geojson.type === "Feature") { callback(geojson, 0); } else if (geojson.type === "FeatureCollection") { for (var i = 0; i < geojson.features.length; i++) { if (callback(geojson.features[i], i) === false) break; } } } /** * Callback for featureReduce * * 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 featureReduceCallback * @param {*} previousValue The accumulated value previously returned in the last invocation * of the callback, or initialValue, if supplied. * @param {Feature} currentFeature The current Feature being processed. * @param {number} featureIndex The current index of the Feature being processed. */ /** * Reduce features in any GeoJSON object, similar to Array.reduce(). * * @name featureReduce * @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON object * @param {Function} callback a method that takes (previousValue, currentFeature, featureIndex) * @param {*} [initialValue] Value to use as the first argument to the first call of the callback. * @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.featureReduce(features, function (previousValue, currentFeature, featureIndex) { * //=previousValue * //=currentFeature * //=featureIndex * return currentFeature * }); */ function featureReduce(geojson, callback, initialValue) { var previousValue = initialValue; featureEach(geojson, function (currentFeature, featureIndex) { if (featureIndex === 0 && initialValue === undefined) previousValue = currentFeature; else previousValue = callback(previousValue, currentFeature, featureIndex); }); return previousValue; } /** * Get all coordinates from any GeoJSON object. * * @name coordAll * @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON object * @returns {Array>} coordinate position array * @example * var features = turf.featureCollection([ * turf.point([26, 37], {foo: 'bar'}), * turf.point([36, 53], {hello: 'world'}) * ]); * * var coords = turf.coordAll(features); * //= [[26, 37], [36, 53]] */ function coordAll(geojson) { var coords = []; coordEach(geojson, function (coord) { coords.push(coord); }); return coords; } /** * Callback for geomEach * * @callback geomEachCallback * @param {Geometry} currentGeometry The current Geometry being processed. * @param {number} featureIndex The current index of the Feature being processed. * @param {Object} featureProperties The current Feature Properties being processed. * @param {Array} featureBBox The current Feature BBox being processed. * @param {number|string} featureId The current Feature Id being processed. */ /** * Iterate over each geometry in any GeoJSON object, similar to Array.forEach() * * @name geomEach * @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON object * @param {Function} callback a method that takes (currentGeometry, featureIndex, featureProperties, featureBBox, featureId) * @returns {void} * @example * var features = turf.featureCollection([ * turf.point([26, 37], {foo: 'bar'}), * turf.point([36, 53], {hello: 'world'}) * ]); * * turf.geomEach(features, function (currentGeometry, featureIndex, featureProperties, featureBBox, featureId) { * //=currentGeometry * //=featureIndex * //=featureProperties * //=featureBBox * //=featureId * }); */ function geomEach(geojson, callback) { var i, j, g, geometry, stopG, geometryMaybeCollection, isGeometryCollection, featureProperties, featureBBox, featureId, featureIndex = 0, isFeatureCollection = geojson.type === "FeatureCollection", isFeature = geojson.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 (i = 0; i < stop; i++) { geometryMaybeCollection = isFeatureCollection ? geojson.features[i].geometry : isFeature ? geojson.geometry : geojson; featureProperties = isFeatureCollection ? geojson.features[i].properties : isFeature ? geojson.properties : {}; featureBBox = isFeatureCollection ? geojson.features[i].bbox : isFeature ? geojson.bbox : undefined; featureId = isFeatureCollection ? geojson.features[i].id : isFeature ? geojson.id : undefined; isGeometryCollection = geometryMaybeCollection ? geometryMaybeCollection.type === "GeometryCollection" : false; stopG = isGeometryCollection ? geometryMaybeCollection.geometries.length : 1; for (g = 0; g < stopG; g++) { geometry = isGeometryCollection ? geometryMaybeCollection.geometries[g] : geometryMaybeCollection; // Handle null Geometry if (geometry === null) { if ( callback( null, featureIndex, featureProperties, featureBBox, featureId ) === false ) return false; continue; } switch (geometry.type) { case "Point": case "LineString": case "MultiPoint": case "Polygon": case "MultiLineString": case "MultiPolygon": { if ( callback( geometry, featureIndex, featureProperties, featureBBox, featureId ) === false ) return false; break; } case "GeometryCollection": { for (j = 0; j < geometry.geometries.length; j++) { if ( callback( geometry.geometries[j], featureIndex, featureProperties, featureBBox, featureId ) === false ) return false; } break; } default: throw new Error("Unknown Geometry Type"); } } // Only increase `featureIndex` per each feature featureIndex++; } } /** * Callback for geomReduce * * 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 geomReduceCallback * @param {*} previousValue The accumulated value previously returned in the last invocation * of the callback, or initialValue, if supplied. * @param {Geometry} currentGeometry The current Geometry being processed. * @param {number} featureIndex The current index of the Feature being processed. * @param {Object} featureProperties The current Feature Properties being processed. * @param {Array} featureBBox The current Feature BBox being processed. * @param {number|string} featureId The current Feature Id being processed. */ /** * Reduce geometry in any GeoJSON object, similar to Array.reduce(). * * @name geomReduce * @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON object * @param {Function} callback a method that takes (previousValue, currentGeometry, featureIndex, featureProperties, featureBBox, featureId) * @param {*} [initialValue] Value to use as the first argument to the first call of the callback. * @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.geomReduce(features, function (previousValue, currentGeometry, featureIndex, featureProperties, featureBBox, featureId) { * //=previousValue * //=currentGeometry * //=featureIndex * //=featureProperties * //=featureBBox * //=featureId * return currentGeometry * }); */ function geomReduce(geojson, callback, initialValue) { var previousValue = initialValue; geomEach( geojson, function ( currentGeometry, featureIndex, featureProperties, featureBBox, featureId ) { if (featureIndex === 0 && initialValue === undefined) previousValue = currentGeometry; else previousValue = callback( previousValue, currentGeometry, featureIndex, featureProperties, featureBBox, featureId ); } ); return previousValue; } /** * Callback for flattenEach * * @callback flattenEachCallback * @param {Feature} currentFeature The current flattened feature 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. */ /** * Iterate over flattened features in any GeoJSON object, similar to * Array.forEach. * * @name flattenEach * @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON object * @param {Function} callback a method that takes (currentFeature, featureIndex, multiFeatureIndex) * @example * var features = turf.featureCollection([ * turf.point([26, 37], {foo: 'bar'}), * turf.multiPoint([[40, 30], [36, 53]], {hello: 'world'}) * ]); * * turf.flattenEach(features, function (currentFeature, featureIndex, multiFeatureIndex) { * //=currentFeature * //=featureIndex * //=multiFeatureIndex * }); */ function flattenEach(geojson, callback) { geomEach(geojson, function (geometry, featureIndex, properties, bbox, id) { // Callback for single geometry var type = geometry === null ? null : geometry.type; switch (type) { case null: case "Point": case "LineString": case "Polygon": if ( callback( helpers.feature(geometry, properties, { bbox: bbox, id: id }), featureIndex, 0 ) === false ) return false; return; } var geomType; // Callback for multi-geometry switch (type) { case "MultiPoint": geomType = "Point"; break; case "MultiLineString": geomType = "LineString"; break; case "MultiPolygon": geomType = "Polygon"; break; } for ( var multiFeatureIndex = 0; multiFeatureIndex < geometry.coordinates.length; multiFeatureIndex++ ) { var coordinate = geometry.coordinates[multiFeatureIndex]; var geom = { type: geomType, coordinates: coordinate, }; if ( callback(helpers.feature(geom, properties), featureIndex, multiFeatureIndex) === false ) return false; } }); } /** * Callback for flattenReduce * * 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 flattenReduceCallback * @param {*} previousValue The accumulated value previously returned in the last invocation * of the callback, or initialValue, if supplied. * @param {Feature} currentFeature The current Feature 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. */ /** * Reduce flattened features in any GeoJSON object, similar to Array.reduce(). * * @name flattenReduce * @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON object * @param {Function} callback a method that takes (previousValue, currentFeature, featureIndex, multiFeatureIndex) * @param {*} [initialValue] Value to use as the first argument to the first call of the callback. * @returns {*} The value that results from the reduction. * @example * var features = turf.featureCollection([ * turf.point([26, 37], {foo: 'bar'}), * turf.multiPoint([[40, 30], [36, 53]], {hello: 'world'}) * ]); * * turf.flattenReduce(features, function (previousValue, currentFeature, featureIndex, multiFeatureIndex) { * //=previousValue * //=currentFeature * //=featureIndex * //=multiFeatureIndex * return currentFeature * }); */ function flattenReduce(geojson, callback, initialValue) { var previousValue = initialValue; flattenEach( geojson, function (currentFeature, featureIndex, multiFeatureIndex) { if ( featureIndex === 0 && multiFeatureIndex === 0 && initialValue === undefined ) previousValue = currentFeature; else previousValue = callback( previousValue, currentFeature, featureIndex, multiFeatureIndex ); } ); return previousValue; } /** * Callback for segmentEach * * @callback segmentEachCallback * @param {Feature} currentSegment The current Segment 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. * @param {number} segmentIndex The current index of the Segment being processed. * @returns {void} */ /** * Iterate over 2-vertex line segment in any GeoJSON object, similar to Array.forEach() * (Multi)Point geometries do not contain segments therefore they are ignored during this operation. * * @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON * @param {Function} callback a method that takes (currentSegment, featureIndex, multiFeatureIndex, geometryIndex, segmentIndex) * @returns {void} * @example * var polygon = turf.polygon([[[-50, 5], [-40, -10], [-50, -10], [-40, 5], [-50, 5]]]); * * // Iterate over GeoJSON by 2-vertex segments * turf.segmentEach(polygon, function (currentSegment, featureIndex, multiFeatureIndex, geometryIndex, segmentIndex) { * //=currentSegment * //=featureIndex * //=multiFeatureIndex * //=geometryIndex * //=segmentIndex * }); * * // Calculate the total number of segments * var total = 0; * turf.segmentEach(polygon, function () { * total++; * }); */ function segmentEach(geojson, callback) { flattenEach(geojson, function (feature, featureIndex, multiFeatureIndex) { var segmentIndex = 0; // Exclude null Geometries if (!feature.geometry) return; // (Multi)Point geometries do not contain segments therefore they are ignored during this operation. var type = feature.geometry.type; if (type === "Point" || type === "MultiPoint") return; // Generate 2-vertex line segments var previousCoords; var previousFeatureIndex = 0; var previousMultiIndex = 0; var prevGeomIndex = 0; if ( coordEach( feature, function ( currentCoord, coordIndex, featureIndexCoord, multiPartIndexCoord, geometryIndex ) { // Simulating a meta.coordReduce() since `reduce` operations cannot be stopped by returning `false` if ( previousCoords === undefined || featureIndex > previousFeatureIndex || multiPartIndexCoord > previousMultiIndex || geometryIndex > prevGeomIndex ) { previousCoords = currentCoord; previousFeatureIndex = featureIndex; previousMultiIndex = multiPartIndexCoord; prevGeomIndex = geometryIndex; segmentIndex = 0; return; } var currentSegment = helpers.lineString( [previousCoords, currentCoord], feature.properties ); if ( callback( currentSegment, featureIndex, multiFeatureIndex, geometryIndex, segmentIndex ) === false ) return false; segmentIndex++; previousCoords = currentCoord; } ) === false ) return false; }); } /** * Callback for segmentReduce * * 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 segmentReduceCallback * @param {*} previousValue The accumulated value previously returned in the last invocation * of the callback, or initialValue, if supplied. * @param {Feature} currentSegment The current Segment 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. * @param {number} segmentIndex The current index of the Segment being processed. */ /** * Reduce 2-vertex line segment in any GeoJSON object, similar to Array.reduce() * (Multi)Point geometries do not contain segments therefore they are ignored during this operation. * * @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON * @param {Function} callback a method that takes (previousValue, currentSegment, currentIndex) * @param {*} [initialValue] Value to use as the first argument to the first call of the callback. * @returns {void} * @example * var polygon = turf.polygon([[[-50, 5], [-40, -10], [-50, -10], [-40, 5], [-50, 5]]]); * * // Iterate over GeoJSON by 2-vertex segments * turf.segmentReduce(polygon, function (previousSegment, currentSegment, featureIndex, multiFeatureIndex, geometryIndex, segmentIndex) { * //= previousSegment * //= currentSegment * //= featureIndex * //= multiFeatureIndex * //= geometryIndex * //= segmentIndex * return currentSegment * }); * * // Calculate the total number of segments * var initialValue = 0 * var total = turf.segmentReduce(polygon, function (previousValue) { * previousValue++; * return previousValue; * }, initialValue); */ function segmentReduce(geojson, callback, initialValue) { var previousValue = initialValue; var started = false; segmentEach( geojson, function ( currentSegment, featureIndex, multiFeatureIndex, geometryIndex, segmentIndex ) { if (started === false && initialValue === undefined) previousValue = currentSegment; else previousValue = callback( previousValue, currentSegment, featureIndex, multiFeatureIndex, geometryIndex, segmentIndex ); started = true; } ); return previousValue; } /** * Callback for lineEach * * @callback lineEachCallback * @param {Feature} currentLine The current LineString|LinearRing 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 line or ring coordinates in LineString, Polygon, MultiLineString, MultiPolygon Features or Geometries, * similar to Array.forEach. * * @name lineEach * @param {Geometry|Feature} geojson object * @param {Function} callback a method that takes (currentLine, featureIndex, multiFeatureIndex, geometryIndex) * @example * var multiLine = turf.multiLineString([ * [[26, 37], [35, 45]], * [[36, 53], [38, 50], [41, 55]] * ]); * * turf.lineEach(multiLine, function (currentLine, featureIndex, multiFeatureIndex, geometryIndex) { * //=currentLine * //=featureIndex * //=multiFeatureIndex * //=geometryIndex * }); */ function lineEach(geojson, callback) { // validation if (!geojson) throw new Error("geojson is required"); flattenEach(geojson, function (feature, featureIndex, multiFeatureIndex) { if (feature.geometry === null) return; var type = feature.geometry.type; var coords = feature.geometry.coordinates; switch (type) { case "LineString": if (callback(feature, featureIndex, multiFeatureIndex, 0, 0) === false) return false; break; case "Polygon": for ( var geometryIndex = 0; geometryIndex < coords.length; geometryIndex++ ) { if ( callback( helpers.lineString(coords[geometryIndex], feature.properties), featureIndex, multiFeatureIndex, geometryIndex ) === false ) return false; } break; } }); } /** * Callback for lineReduce * * 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 lineReduceCallback * @param {*} previousValue The accumulated value previously returned in the last invocation * of the callback, or initialValue, if supplied. * @param {Feature} currentLine The current LineString|LinearRing 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 */ /** * Reduce features in any GeoJSON object, similar to Array.reduce(). * * @name lineReduce * @param {Geometry|Feature} geojson object * @param {Function} callback a method that takes (previousValue, currentLine, featureIndex, multiFeatureIndex, geometryIndex) * @param {*} [initialValue] Value to use as the first argument to the first call of the callback. * @returns {*} The value that results from the reduction. * @example * var multiPoly = turf.multiPolygon([ * turf.polygon([[[12,48],[2,41],[24,38],[12,48]], [[9,44],[13,41],[13,45],[9,44]]]), * turf.polygon([[[5, 5], [0, 0], [2, 2], [4, 4], [5, 5]]]) * ]); * * turf.lineReduce(multiPoly, function (previousValue, currentLine, featureIndex, multiFeatureIndex, geometryIndex) { * //=previousValue * //=currentLine * //=featureIndex * //=multiFeatureIndex * //=geometryIndex * return currentLine * }); */ function lineReduce(geojson, callback, initialValue) { var previousValue = initialValue; lineEach( geojson, function (currentLine, featureIndex, multiFeatureIndex, geometryIndex) { if (featureIndex === 0 && initialValue === undefined) previousValue = currentLine; else previousValue = callback( previousValue, currentLine, featureIndex, multiFeatureIndex, geometryIndex ); } ); return previousValue; } /** * Finds a particular 2-vertex LineString Segment from a GeoJSON using `@turf/meta` indexes. * * Negative indexes are permitted. * Point & MultiPoint will always return null. * * @param {FeatureCollection|Feature|Geometry} geojson Any GeoJSON Feature or Geometry * @param {Object} [options={}] Optional parameters * @param {number} [options.featureIndex=0] Feature Index * @param {number} [options.multiFeatureIndex=0] Multi-Feature Index * @param {number} [options.geometryIndex=0] Geometry Index * @param {number} [options.segmentIndex=0] Segment Index * @param {Object} [options.properties={}] Translate Properties to output LineString * @param {BBox} [options.bbox={}] Translate BBox to output LineString * @param {number|string} [options.id={}] Translate Id to output LineString * @returns {Feature} 2-vertex GeoJSON Feature LineString * @example * var multiLine = turf.multiLineString([ * [[10, 10], [50, 30], [30, 40]], * [[-10, -10], [-50, -30], [-30, -40]] * ]); * * // First Segment (defaults are 0) * turf.findSegment(multiLine); * // => Feature> * * // First Segment of 2nd Multi Feature * turf.findSegment(multiLine, {multiFeatureIndex: 1}); * // => Feature> * * // Last Segment of Last Multi Feature * turf.findSegment(multiLine, {multiFeatureIndex: -1, segmentIndex: -1}); * // => Feature> */ function findSegment(geojson, options) { // Optional Parameters options = options || {}; if (!helpers.isObject(options)) throw new Error("options is invalid"); var featureIndex = options.featureIndex || 0; var multiFeatureIndex = options.multiFeatureIndex || 0; var geometryIndex = options.geometryIndex || 0; var segmentIndex = options.segmentIndex || 0; // Find FeatureIndex var properties = options.properties; var geometry; switch (geojson.type) { case "FeatureCollection": if (featureIndex < 0) featureIndex = geojson.features.length + featureIndex; properties = properties || geojson.features[featureIndex].properties; geometry = geojson.features[featureIndex].geometry; break; case "Feature": properties = properties || geojson.properties; geometry = geojson.geometry; break; case "Point": case "MultiPoint": return null; case "LineString": case "Polygon": case "MultiLineString": case "MultiPolygon": geometry = geojson; break; default: throw new Error("geojson is invalid"); } // Find SegmentIndex if (geometry === null) return null; var coords = geometry.coordinates; switch (geometry.type) { case "Point": case "MultiPoint": return null; case "LineString": if (segmentIndex < 0) segmentIndex = coords.length + segmentIndex - 1; return helpers.lineString( [coords[segmentIndex], coords[segmentIndex + 1]], properties, options ); case "Polygon": if (geometryIndex < 0) geometryIndex = coords.length + geometryIndex; if (segmentIndex < 0) segmentIndex = coords[geometryIndex].length + segmentIndex - 1; return helpers.lineString( [ coords[geometryIndex][segmentIndex], coords[geometryIndex][segmentIndex + 1], ], properties, options ); case "MultiLineString": if (multiFeatureIndex < 0) multiFeatureIndex = coords.length + multiFeatureIndex; if (segmentIndex < 0) segmentIndex = coords[multiFeatureIndex].length + segmentIndex - 1; return helpers.lineString( [ coords[multiFeatureIndex][segmentIndex], coords[multiFeatureIndex][segmentIndex + 1], ], properties, options ); case "MultiPolygon": if (multiFeatureIndex < 0) multiFeatureIndex = coords.length + multiFeatureIndex; if (geometryIndex < 0) geometryIndex = coords[multiFeatureIndex].length + geometryIndex; if (segmentIndex < 0) segmentIndex = coords[multiFeatureIndex][geometryIndex].length - segmentIndex - 1; return helpers.lineString( [ coords[multiFeatureIndex][geometryIndex][segmentIndex], coords[multiFeatureIndex][geometryIndex][segmentIndex + 1], ], properties, options ); } throw new Error("geojson is invalid"); } /** * Finds a particular Point from a GeoJSON using `@turf/meta` indexes. * * Negative indexes are permitted. * * @param {FeatureCollection|Feature|Geometry} geojson Any GeoJSON Feature or Geometry * @param {Object} [options={}] Optional parameters * @param {number} [options.featureIndex=0] Feature Index * @param {number} [options.multiFeatureIndex=0] Multi-Feature Index * @param {number} [options.geometryIndex=0] Geometry Index * @param {number} [options.coordIndex=0] Coord Index * @param {Object} [options.properties={}] Translate Properties to output Point * @param {BBox} [options.bbox={}] Translate BBox to output Point * @param {number|string} [options.id={}] Translate Id to output Point * @returns {Feature} 2-vertex GeoJSON Feature Point * @example * var multiLine = turf.multiLineString([ * [[10, 10], [50, 30], [30, 40]], * [[-10, -10], [-50, -30], [-30, -40]] * ]); * * // First Segment (defaults are 0) * turf.findPoint(multiLine); * // => Feature> * * // First Segment of the 2nd Multi-Feature * turf.findPoint(multiLine, {multiFeatureIndex: 1}); * // => Feature> * * // Last Segment of last Multi-Feature * turf.findPoint(multiLine, {multiFeatureIndex: -1, coordIndex: -1}); * // => Feature> */ function findPoint(geojson, options) { // Optional Parameters options = options || {}; if (!helpers.isObject(options)) throw new Error("options is invalid"); var featureIndex = options.featureIndex || 0; var multiFeatureIndex = options.multiFeatureIndex || 0; var geometryIndex = options.geometryIndex || 0; var coordIndex = options.coordIndex || 0; // Find FeatureIndex var properties = options.properties; var geometry; switch (geojson.type) { case "FeatureCollection": if (featureIndex < 0) featureIndex = geojson.features.length + featureIndex; properties = properties || geojson.features[featureIndex].properties; geometry = geojson.features[featureIndex].geometry; break; case "Feature": properties = properties || geojson.properties; geometry = geojson.geometry; break; case "Point": case "MultiPoint": return null; case "LineString": case "Polygon": case "MultiLineString": case "MultiPolygon": geometry = geojson; break; default: throw new Error("geojson is invalid"); } // Find Coord Index if (geometry === null) return null; var coords = geometry.coordinates; switch (geometry.type) { case "Point": return helpers.point(coords, properties, options); case "MultiPoint": if (multiFeatureIndex < 0) multiFeatureIndex = coords.length + multiFeatureIndex; return helpers.point(coords[multiFeatureIndex], properties, options); case "LineString": if (coordIndex < 0) coordIndex = coords.length + coordIndex; return helpers.point(coords[coordIndex], properties, options); case "Polygon": if (geometryIndex < 0) geometryIndex = coords.length + geometryIndex; if (coordIndex < 0) coordIndex = coords[geometryIndex].length + coordIndex; return helpers.point(coords[geometryIndex][coordIndex], properties, options); case "MultiLineString": if (multiFeatureIndex < 0) multiFeatureIndex = coords.length + multiFeatureIndex; if (coordIndex < 0) coordIndex = coords[multiFeatureIndex].length + coordIndex; return helpers.point(coords[multiFeatureIndex][coordIndex], properties, options); case "MultiPolygon": if (multiFeatureIndex < 0) multiFeatureIndex = coords.length + multiFeatureIndex; if (geometryIndex < 0) geometryIndex = coords[multiFeatureIndex].length + geometryIndex; if (coordIndex < 0) coordIndex = coords[multiFeatureIndex][geometryIndex].length - coordIndex; return helpers.point( coords[multiFeatureIndex][geometryIndex][coordIndex], properties, options ); } throw new Error("geojson is invalid"); } exports.coordAll = coordAll; exports.coordEach = coordEach; exports.coordReduce = coordReduce; exports.featureEach = featureEach; exports.featureReduce = featureReduce; exports.findPoint = findPoint; exports.findSegment = findSegment; exports.flattenEach = flattenEach; exports.flattenReduce = flattenReduce; exports.geomEach = geomEach; exports.geomReduce = geomReduce; exports.lineEach = lineEach; exports.lineReduce = lineReduce; exports.propEach = propEach; exports.propReduce = propReduce; exports.segmentEach = segmentEach; exports.segmentReduce = segmentReduce; /***/ }), /***/ 5748: /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) { "use strict"; // ESM COMPAT FLAG __webpack_require__.r(__webpack_exports__); // EXPORTS __webpack_require__.d(__webpack_exports__, { "default": function() { return /* binding */ transform_scale_main_es; } }); ;// CONCATENATED MODULE: ./node_modules/@turf/clone/main.es.js /** * Returns a cloned copy of the passed GeoJSON Object, including possible 'Foreign Members'. * ~3-5x faster than the common JSON.parse + JSON.stringify combo method. * * @name clone * @param {GeoJSON} geojson GeoJSON Object * @returns {GeoJSON} cloned GeoJSON Object * @example * var line = turf.lineString([[-74, 40], [-78, 42], [-82, 35]], {color: 'red'}); * * var lineCloned = turf.clone(line); */ function clone(geojson) { if (!geojson) throw new Error('geojson is required'); switch (geojson.type) { case 'Feature': return cloneFeature(geojson); case 'FeatureCollection': return cloneFeatureCollection(geojson); case 'Point': case 'LineString': case 'Polygon': case 'MultiPoint': case 'MultiLineString': case 'MultiPolygon': case 'GeometryCollection': return cloneGeometry(geojson); default: throw new Error('unknown GeoJSON type'); } } /** * Clone Feature * * @private * @param {Feature} geojson GeoJSON Feature * @returns {Feature} cloned Feature */ function cloneFeature(geojson) { var cloned = {type: 'Feature'}; // Preserve Foreign Members Object.keys(geojson).forEach(function (key) { switch (key) { case 'type': case 'properties': case 'geometry': return; default: cloned[key] = geojson[key]; } }); // Add properties & geometry last cloned.properties = cloneProperties(geojson.properties); cloned.geometry = cloneGeometry(geojson.geometry); return cloned; } /** * Clone Properties * * @private * @param {Object} properties GeoJSON Properties * @returns {Object} cloned Properties */ function cloneProperties(properties) { var cloned = {}; if (!properties) return cloned; Object.keys(properties).forEach(function (key) { var value = properties[key]; if (typeof value === 'object') { if (value === null) { // handle null cloned[key] = null; } else if (value.length) { // handle Array cloned[key] = value.map(function (item) { return item; }); } else { // handle generic Object cloned[key] = cloneProperties(value); } } else cloned[key] = value; }); return cloned; } /** * Clone Feature Collection * * @private * @param {FeatureCollection} geojson GeoJSON Feature Collection * @returns {FeatureCollection} cloned Feature Collection */ function cloneFeatureCollection(geojson) { var cloned = {type: 'FeatureCollection'}; // Preserve Foreign Members Object.keys(geojson).forEach(function (key) { switch (key) { case 'type': case 'features': return; default: cloned[key] = geojson[key]; } }); // Add features cloned.features = geojson.features.map(function (feature) { return cloneFeature(feature); }); return cloned; } /** * Clone Geometry * * @private * @param {Geometry} geometry GeoJSON Geometry * @returns {Geometry} cloned Geometry */ function cloneGeometry(geometry) { var geom = {type: geometry.type}; if (geometry.bbox) geom.bbox = geometry.bbox; if (geometry.type === 'GeometryCollection') { geom.geometries = geometry.geometries.map(function (geom) { return cloneGeometry(geom); }); return geom; } geom.coordinates = deepSlice(geometry.coordinates); return geom; } /** * Deep Slice coordinates * * @private * @param {Coordinates} coords Coordinates * @returns {Coordinates} all coordinates sliced */ function deepSlice(coords) { if (typeof coords[0] !== 'object') { return coords.slice(); } return coords.map(function (coord) { return deepSlice(coord); }); } /* harmony default export */ var main_es = (clone); ;// CONCATENATED MODULE: ./node_modules/@turf/center/node_modules/@turf/helpers/main.es.js /** * Earth Radius used with the Harvesine formula and approximates using a spherical (non-ellipsoid) Earth. */ var earthRadius = 6371008.8; /** * Unit of measurement factors using a spherical (non-ellipsoid) earth radius. */ var factors = { meters: earthRadius, metres: earthRadius, millimeters: earthRadius * 1000, millimetres: earthRadius * 1000, centimeters: earthRadius * 100, centimetres: earthRadius * 100, kilometers: earthRadius / 1000, kilometres: earthRadius / 1000, miles: earthRadius / 1609.344, nauticalmiles: earthRadius / 1852, inches: earthRadius * 39.370, yards: earthRadius / 1.0936, feet: earthRadius * 3.28084, radians: 1, degrees: earthRadius / 111325, }; /** * Units of measurement factors based on 1 meter. */ var unitsFactors = { meters: 1, metres: 1, millimeters: 1000, millimetres: 1000, centimeters: 100, centimetres: 100, kilometers: 1 / 1000, kilometres: 1 / 1000, miles: 1 / 1609.344, nauticalmiles: 1 / 1852, inches: 39.370, yards: 1 / 1.0936, feet: 3.28084, radians: 1 / earthRadius, degrees: 1 / 111325, }; /** * Area of measurement factors based on 1 square meter. */ var areaFactors = { meters: 1, metres: 1, millimeters: 1000000, millimetres: 1000000, centimeters: 10000, centimetres: 10000, kilometers: 0.000001, kilometres: 0.000001, acres: 0.000247105, miles: 3.86e-7, yards: 1.195990046, feet: 10.763910417, inches: 1550.003100006 }; /** * 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} [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 main_es_feature(geometry, properties, options) { // Optional Parameters options = options || {}; if (!main_es_isObject(options)) throw new Error('options is invalid'); var bbox = options.bbox; var id = options.id; // Validation if (geometry === undefined) throw new Error('geometry is required'); if (properties && properties.constructor !== Object) throw new Error('properties must be an Object'); if (bbox) validateBBox(bbox); if (id) validateId(id); // Main var feat = {type: 'Feature'}; if (id) feat.id = id; if (bbox) feat.bbox = bbox; feat.properties = properties || {}; feat.geometry = geometry; return feat; } /** * 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} coordinates Coordinates * @param {Object} [options={}] Optional Parameters * @param {Array} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Geometry * @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) { // Optional Parameters options = options || {}; if (!main_es_isObject(options)) throw new Error('options is invalid'); var bbox = options.bbox; // Validation if (!type) throw new Error('type is required'); if (!coordinates) throw new Error('coordinates is required'); if (!Array.isArray(coordinates)) throw new Error('coordinates must be an Array'); if (bbox) validateBBox(bbox); // Main var geom; switch (type) { case 'Point': geom = main_es_point(coordinates).geometry; break; case 'LineString': geom = main_es_lineString(coordinates).geometry; break; case 'Polygon': geom = polygon(coordinates).geometry; break; case 'MultiPoint': geom = multiPoint(coordinates).geometry; break; case 'MultiLineString': geom = multiLineString(coordinates).geometry; break; case 'MultiPolygon': geom = multiPolygon(coordinates).geometry; break; default: throw new Error(type + ' is invalid'); } if (bbox) geom.bbox = bbox; return geom; } /** * Creates a {@link Point} {@link Feature} from a Position. * * @name point * @param {Array} 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} [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 Point feature * @example * var point = turf.point([-75.343, 39.984]); * * //=point */ function main_es_point(coordinates, properties, options) { if (!coordinates) throw new Error('coordinates is required'); if (!Array.isArray(coordinates)) throw new Error('coordinates must be an Array'); if (coordinates.length < 2) throw new Error('coordinates must be at least 2 numbers long'); if (!main_es_isNumber(coordinates[0]) || !main_es_isNumber(coordinates[1])) throw new Error('coordinates must contain numbers'); return main_es_feature({ type: 'Point', coordinates: coordinates }, properties, options); } /** * Creates a {@link Point} {@link FeatureCollection} from an Array of Point coordinates. * * @name points * @param {Array>} coordinates an array of Points * @param {Object} [properties={}] Translate these properties to each Feature * @param {Object} [options={}] Optional Parameters * @param {Array} [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 Feature * @example * var points = turf.points([ * [-75, 39], * [-80, 45], * [-78, 50] * ]); * * //=points */ function points(coordinates, properties, options) { if (!coordinates) throw new Error('coordinates is required'); if (!Array.isArray(coordinates)) throw new Error('coordinates must be an Array'); return featureCollection(coordinates.map(function (coords) { return main_es_point(coords, properties); }), options); } /** * Creates a {@link Polygon} {@link Feature} from an Array of LinearRings. * * @name polygon * @param {Array>>} 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} [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 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 (!coordinates) throw new Error('coordinates is required'); for (var i = 0; i < coordinates.length; i++) { var ring = coordinates[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 (i === 0 && j === 0 && !main_es_isNumber(ring[0][0]) || !main_es_isNumber(ring[0][1])) throw new Error('coordinates must contain numbers'); if (ring[ring.length - 1][j] !== ring[0][j]) { throw new Error('First and last Position are not equivalent.'); } } } return main_es_feature({ type: 'Polygon', coordinates: coordinates }, properties, options); } /** * Creates a {@link Polygon} {@link FeatureCollection} from an Array of Polygon coordinates. * * @name polygons * @param {Array>>>} 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} [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 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 (!coordinates) throw new Error('coordinates is required'); if (!Array.isArray(coordinates)) throw new Error('coordinates must be an Array'); return featureCollection(coordinates.map(function (coords) { return polygon(coords, properties); }), options); } /** * Creates a {@link LineString} {@link Feature} from an Array of Positions. * * @name lineString * @param {Array>} 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} [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 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 main_es_lineString(coordinates, properties, options) { if (!coordinates) throw new Error('coordinates is required'); if (coordinates.length < 2) throw new Error('coordinates must be an array of two or more positions'); // Check if first point of LineString contains two numbers if (!main_es_isNumber(coordinates[0][1]) || !main_es_isNumber(coordinates[0][1])) throw new Error('coordinates must contain numbers'); return main_es_feature({ type: 'LineString', coordinates: coordinates }, properties, options); } /** * Creates a {@link LineString} {@link FeatureCollection} from an Array of LineString coordinates. * * @name lineStrings * @param {Array>} 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} [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 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 (!coordinates) throw new Error('coordinates is required'); if (!Array.isArray(coordinates)) throw new Error('coordinates must be an Array'); return featureCollection(coordinates.map(function (coords) { return main_es_lineString(coords, properties); }), options); } /** * 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} [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) { // Optional Parameters options = options || {}; if (!main_es_isObject(options)) throw new Error('options is invalid'); var bbox = options.bbox; var id = options.id; // Validation if (!features) throw new Error('No features passed'); if (!Array.isArray(features)) throw new Error('features must be an Array'); if (bbox) validateBBox(bbox); if (id) validateId(id); // Main var fc = {type: 'FeatureCollection'}; if (id) fc.id = id; if (bbox) fc.bbox = bbox; fc.features = features; return fc; } /** * Creates a {@link Feature} based on a * coordinate array. Properties can be added optionally. * * @name multiLineString * @param {Array>>} 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} [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 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 (!coordinates) throw new Error('coordinates is required'); return main_es_feature({ type: 'MultiLineString', coordinates: coordinates }, properties, options); } /** * Creates a {@link Feature} based on a * coordinate array. Properties can be added optionally. * * @name multiPoint * @param {Array>} 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} [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 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 (!coordinates) throw new Error('coordinates is required'); return main_es_feature({ type: 'MultiPoint', coordinates: coordinates }, properties, options); } /** * Creates a {@link Feature} based on a * coordinate array. Properties can be added optionally. * * @name multiPolygon * @param {Array>>>} 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} [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 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 (!coordinates) throw new Error('coordinates is required'); return main_es_feature({ type: 'MultiPolygon', coordinates: coordinates }, properties, options); } /** * Creates a {@link Feature} based on a * coordinate array. Properties can be added optionally. * * @name geometryCollection * @param {Array} 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} [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 GeometryCollection Feature * @example * var pt = { * "type": "Point", * "coordinates": [100, 0] * }; * var line = { * "type": "LineString", * "coordinates": [ [101, 0], [102, 1] ] * }; * var collection = turf.geometryCollection([pt, line]); * * //=collection */ function geometryCollection(geometries, properties, options) { if (!geometries) throw new Error('geometries is required'); if (!Array.isArray(geometries)) throw new Error('geometries must be an Array'); return main_es_feature({ type: 'GeometryCollection', geometries: geometries }, properties, options); } /** * 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 (num === undefined || num === null || isNaN(num)) throw new Error('num is required'); 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; } /** * 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 (radians === undefined || radians === null) throw new Error('radians is required'); if (units && typeof units !== 'string') throw new Error('units must be a string'); var factor = factors[units || 'kilometers']; if (!factor) throw new Error(units + ' units is invalid'); return radians * factor; } /** * 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 (distance === undefined || distance === null) throw new Error('distance is required'); if (units && typeof units !== 'string') throw new Error('units must be a string'); var factor = factors[units || 'kilometers']; if (!factor) throw new Error(units + ' units is invalid'); return distance / factor; } /** * 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)); } /** * 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) { if (bearing === null || bearing === undefined) throw new Error('bearing is required'); var angle = bearing % 360; if (angle < 0) angle += 360; return angle; } /** * 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) { if (radians === null || radians === undefined) throw new Error('radians is required'); var degrees = radians % (2 * Math.PI); return degrees * 180 / Math.PI; } /** * 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) { if (degrees === null || degrees === undefined) throw new Error('degrees is required'); var radians = degrees % 360; return radians * Math.PI / 180; } /** * 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 {string} originalUnit of the length * @param {string} [finalUnit='kilometers'] returned unit * @returns {number} the converted length */ function convertLength(length, originalUnit, finalUnit) { if (length === null || length === undefined) throw new Error('length is required'); if (!(length >= 0)) throw new Error('length must be a positive number'); return radiansToLength(lengthToRadians(length, originalUnit), finalUnit || 'kilometers'); } /** * 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 {string} [originalUnit='meters'] of the distance * @param {string} [finalUnit='kilometers'] returned unit * @returns {number} the converted distance */ function convertArea(area, originalUnit, finalUnit) { if (area === null || area === undefined) throw new Error('area is required'); if (!(area >= 0)) throw new Error('area must be a positive number'); var startFactor = areaFactors[originalUnit || 'meters']; if (!startFactor) throw new Error('invalid original units'); var finalFactor = areaFactors[finalUnit || 'kilometers']; if (!finalFactor) throw new Error('invalid final units'); return (area / startFactor) * finalFactor; } /** * isNumber * * @param {*} num Number to validate * @returns {boolean} true/false * @example * turf.isNumber(123) * //=true * turf.isNumber('foo') * //=false */ function main_es_isNumber(num) { return !isNaN(num) && num !== null && !Array.isArray(num); } /** * isObject * * @param {*} input variable to validate * @returns {boolean} true/false * @example * turf.isObject({elevation: 10}) * //=true * turf.isObject('foo') * //=false */ function main_es_isObject(input) { return (!!input) && (input.constructor === Object); } /** * Validate BBox * * @private * @param {Array} 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 (!main_es_isNumber(num)) throw new Error('bbox must only contain numbers'); }); } /** * 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'); } // Deprecated methods function radians2degrees() { throw new Error('method has been renamed to `radiansToDegrees`'); } function degrees2radians() { throw new Error('method has been renamed to `degreesToRadians`'); } function distanceToDegrees() { throw new Error('method has been renamed to `lengthToDegrees`'); } function distanceToRadians() { throw new Error('method has been renamed to `lengthToRadians`'); } function radiansToDistance() { throw new Error('method has been renamed to `radiansToLength`'); } function bearingToAngle() { throw new Error('method has been renamed to `bearingToAzimuth`'); } function convertDistance() { throw new Error('method has been renamed to `convertLength`'); } ;// CONCATENATED MODULE: ./node_modules/@turf/center/node_modules/@turf/meta/main.es.js /** * Callback for coordEach * * @callback coordEachCallback * @param {Array} 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++) { if (geomType === 'MultiPolygon') 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} 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|Feature} geojson any GeoJSON object * @param {Function} callback a method that takes (previousValue, currentProperties, featureIndex) * @param {*} [initialValue] Value to use as the first argument to the first call of the callback. * @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.propReduce(features, function (previousValue, currentProperties, featureIndex) { * //=previousValue * //=currentProperties * //=featureIndex * return currentProperties * }); */ function propReduce(geojson, callback, initialValue) { var previousValue = initialValue; propEach(geojson, function (currentProperties, featureIndex) { if (featureIndex === 0 && initialValue === undefined) previousValue = currentProperties; else previousValue = callback(previousValue, currentProperties, featureIndex); }); return previousValue; } /** * Callback for featureEach * * @callback featureEachCallback * @param {Feature} currentFeature The current Feature being processed. * @param {number} featureIndex The current index of the Feature being processed. */ /** * Iterate over features in any GeoJSON object, similar to * Array.forEach. * * @name featureEach * @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON object * @param {Function} callback a method that takes (currentFeature, featureIndex) * @returns {void} * @example * var features = turf.featureCollection([ * turf.point([26, 37], {foo: 'bar'}), * turf.point([36, 53], {hello: 'world'}) * ]); * * turf.featureEach(features, function (currentFeature, featureIndex) { * //=currentFeature * //=featureIndex * }); */ function featureEach(geojson, callback) { if (geojson.type === 'Feature') { callback(geojson, 0); } else if (geojson.type === 'FeatureCollection') { for (var i = 0; i < geojson.features.length; i++) { if (callback(geojson.features[i], i) === false) break; } } } /** * Callback for featureReduce * * 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 featureReduceCallback * @param {*} previousValue The accumulated value previously returned in the last invocation * of the callback, or initialValue, if supplied. * @param {Feature} currentFeature The current Feature being processed. * @param {number} featureIndex The current index of the Feature being processed. */ /** * Reduce features in any GeoJSON object, similar to Array.reduce(). * * @name featureReduce * @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON object * @param {Function} callback a method that takes (previousValue, currentFeature, featureIndex) * @param {*} [initialValue] Value to use as the first argument to the first call of the callback. * @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.featureReduce(features, function (previousValue, currentFeature, featureIndex) { * //=previousValue * //=currentFeature * //=featureIndex * return currentFeature * }); */ function featureReduce(geojson, callback, initialValue) { var previousValue = initialValue; featureEach(geojson, function (currentFeature, featureIndex) { if (featureIndex === 0 && initialValue === undefined) previousValue = currentFeature; else previousValue = callback(previousValue, currentFeature, featureIndex); }); return previousValue; } /** * Get all coordinates from any GeoJSON object. * * @name coordAll * @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON object * @returns {Array>} coordinate position array * @example * var features = turf.featureCollection([ * turf.point([26, 37], {foo: 'bar'}), * turf.point([36, 53], {hello: 'world'}) * ]); * * var coords = turf.coordAll(features); * //= [[26, 37], [36, 53]] */ function coordAll(geojson) { var coords = []; coordEach(geojson, function (coord) { coords.push(coord); }); return coords; } /** * Callback for geomEach * * @callback geomEachCallback * @param {Geometry} currentGeometry The current Geometry being processed. * @param {number} featureIndex The current index of the Feature being processed. * @param {Object} featureProperties The current Feature Properties being processed. * @param {Array} featureBBox The current Feature BBox being processed. * @param {number|string} featureId The current Feature Id being processed. */ /** * Iterate over each geometry in any GeoJSON object, similar to Array.forEach() * * @name geomEach * @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON object * @param {Function} callback a method that takes (currentGeometry, featureIndex, featureProperties, featureBBox, featureId) * @returns {void} * @example * var features = turf.featureCollection([ * turf.point([26, 37], {foo: 'bar'}), * turf.point([36, 53], {hello: 'world'}) * ]); * * turf.geomEach(features, function (currentGeometry, featureIndex, featureProperties, featureBBox, featureId) { * //=currentGeometry * //=featureIndex * //=featureProperties * //=featureBBox * //=featureId * }); */ function geomEach(geojson, callback) { var i, j, g, geometry, stopG, geometryMaybeCollection, isGeometryCollection, featureProperties, featureBBox, featureId, featureIndex = 0, isFeatureCollection = geojson.type === 'FeatureCollection', isFeature = geojson.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 (i = 0; i < stop; i++) { geometryMaybeCollection = (isFeatureCollection ? geojson.features[i].geometry : (isFeature ? geojson.geometry : geojson)); featureProperties = (isFeatureCollection ? geojson.features[i].properties : (isFeature ? geojson.properties : {})); featureBBox = (isFeatureCollection ? geojson.features[i].bbox : (isFeature ? geojson.bbox : undefined)); featureId = (isFeatureCollection ? geojson.features[i].id : (isFeature ? geojson.id : undefined)); isGeometryCollection = (geometryMaybeCollection) ? geometryMaybeCollection.type === 'GeometryCollection' : false; stopG = isGeometryCollection ? geometryMaybeCollection.geometries.length : 1; for (g = 0; g < stopG; g++) { geometry = isGeometryCollection ? geometryMaybeCollection.geometries[g] : geometryMaybeCollection; // Handle null Geometry if (geometry === null) { if (callback(null, featureIndex, featureProperties, featureBBox, featureId) === false) return false; continue; } switch (geometry.type) { case 'Point': case 'LineString': case 'MultiPoint': case 'Polygon': case 'MultiLineString': case 'MultiPolygon': { if (callback(geometry, featureIndex, featureProperties, featureBBox, featureId) === false) return false; break; } case 'GeometryCollection': { for (j = 0; j < geometry.geometries.length; j++) { if (callback(geometry.geometries[j], featureIndex, featureProperties, featureBBox, featureId) === false) return false; } break; } default: throw new Error('Unknown Geometry Type'); } } // Only increase `featureIndex` per each feature featureIndex++; } } /** * Callback for geomReduce * * 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 geomReduceCallback * @param {*} previousValue The accumulated value previously returned in the last invocation * of the callback, or initialValue, if supplied. * @param {Geometry} currentGeometry The current Geometry being processed. * @param {number} featureIndex The current index of the Feature being processed. * @param {Object} featureProperties The current Feature Properties being processed. * @param {Array} featureBBox The current Feature BBox being processed. * @param {number|string} featureId The current Feature Id being processed. */ /** * Reduce geometry in any GeoJSON object, similar to Array.reduce(). * * @name geomReduce * @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON object * @param {Function} callback a method that takes (previousValue, currentGeometry, featureIndex, featureProperties, featureBBox, featureId) * @param {*} [initialValue] Value to use as the first argument to the first call of the callback. * @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.geomReduce(features, function (previousValue, currentGeometry, featureIndex, featureProperties, featureBBox, featureId) { * //=previousValue * //=currentGeometry * //=featureIndex * //=featureProperties * //=featureBBox * //=featureId * return currentGeometry * }); */ function geomReduce(geojson, callback, initialValue) { var previousValue = initialValue; geomEach(geojson, function (currentGeometry, featureIndex, featureProperties, featureBBox, featureId) { if (featureIndex === 0 && initialValue === undefined) previousValue = currentGeometry; else previousValue = callback(previousValue, currentGeometry, featureIndex, featureProperties, featureBBox, featureId); }); return previousValue; } /** * Callback for flattenEach * * @callback flattenEachCallback * @param {Feature} currentFeature The current flattened feature 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. */ /** * Iterate over flattened features in any GeoJSON object, similar to * Array.forEach. * * @name flattenEach * @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON object * @param {Function} callback a method that takes (currentFeature, featureIndex, multiFeatureIndex) * @example * var features = turf.featureCollection([ * turf.point([26, 37], {foo: 'bar'}), * turf.multiPoint([[40, 30], [36, 53]], {hello: 'world'}) * ]); * * turf.flattenEach(features, function (currentFeature, featureIndex, multiFeatureIndex) { * //=currentFeature * //=featureIndex * //=multiFeatureIndex * }); */ function flattenEach(geojson, callback) { geomEach(geojson, function (geometry, featureIndex, properties, bbox, id) { // Callback for single geometry var type = (geometry === null) ? null : geometry.type; switch (type) { case null: case 'Point': case 'LineString': case 'Polygon': if (callback(feature(geometry, properties, {bbox: bbox, id: id}), featureIndex, 0) === false) return false; return; } var geomType; // Callback for multi-geometry switch (type) { case 'MultiPoint': geomType = 'Point'; break; case 'MultiLineString': geomType = 'LineString'; break; case 'MultiPolygon': geomType = 'Polygon'; break; } for (var multiFeatureIndex = 0; multiFeatureIndex < geometry.coordinates.length; multiFeatureIndex++) { var coordinate = geometry.coordinates[multiFeatureIndex]; var geom = { type: geomType, coordinates: coordinate }; if (callback(feature(geom, properties), featureIndex, multiFeatureIndex) === false) return false; } }); } /** * Callback for flattenReduce * * 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 flattenReduceCallback * @param {*} previousValue The accumulated value previously returned in the last invocation * of the callback, or initialValue, if supplied. * @param {Feature} currentFeature The current Feature 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. */ /** * Reduce flattened features in any GeoJSON object, similar to Array.reduce(). * * @name flattenReduce * @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON object * @param {Function} callback a method that takes (previousValue, currentFeature, featureIndex, multiFeatureIndex) * @param {*} [initialValue] Value to use as the first argument to the first call of the callback. * @returns {*} The value that results from the reduction. * @example * var features = turf.featureCollection([ * turf.point([26, 37], {foo: 'bar'}), * turf.multiPoint([[40, 30], [36, 53]], {hello: 'world'}) * ]); * * turf.flattenReduce(features, function (previousValue, currentFeature, featureIndex, multiFeatureIndex) { * //=previousValue * //=currentFeature * //=featureIndex * //=multiFeatureIndex * return currentFeature * }); */ function flattenReduce(geojson, callback, initialValue) { var previousValue = initialValue; flattenEach(geojson, function (currentFeature, featureIndex, multiFeatureIndex) { if (featureIndex === 0 && multiFeatureIndex === 0 && initialValue === undefined) previousValue = currentFeature; else previousValue = callback(previousValue, currentFeature, featureIndex, multiFeatureIndex); }); return previousValue; } /** * Callback for segmentEach * * @callback segmentEachCallback * @param {Feature} currentSegment The current Segment 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. * @param {number} segmentIndex The current index of the Segment being processed. * @returns {void} */ /** * Iterate over 2-vertex line segment in any GeoJSON object, similar to Array.forEach() * (Multi)Point geometries do not contain segments therefore they are ignored during this operation. * * @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON * @param {Function} callback a method that takes (currentSegment, featureIndex, multiFeatureIndex, geometryIndex, segmentIndex) * @returns {void} * @example * var polygon = turf.polygon([[[-50, 5], [-40, -10], [-50, -10], [-40, 5], [-50, 5]]]); * * // Iterate over GeoJSON by 2-vertex segments * turf.segmentEach(polygon, function (currentSegment, featureIndex, multiFeatureIndex, geometryIndex, segmentIndex) { * //=currentSegment * //=featureIndex * //=multiFeatureIndex * //=geometryIndex * //=segmentIndex * }); * * // Calculate the total number of segments * var total = 0; * turf.segmentEach(polygon, function () { * total++; * }); */ function segmentEach(geojson, callback) { flattenEach(geojson, function (feature$$1, featureIndex, multiFeatureIndex) { var segmentIndex = 0; // Exclude null Geometries if (!feature$$1.geometry) return; // (Multi)Point geometries do not contain segments therefore they are ignored during this operation. var type = feature$$1.geometry.type; if (type === 'Point' || type === 'MultiPoint') return; // Generate 2-vertex line segments var previousCoords; if (coordEach(feature$$1, function (currentCoord, coordIndex, featureIndexCoord, mutliPartIndexCoord, geometryIndex) { // Simulating a meta.coordReduce() since `reduce` operations cannot be stopped by returning `false` if (previousCoords === undefined) { previousCoords = currentCoord; return; } var currentSegment = lineString([previousCoords, currentCoord], feature$$1.properties); if (callback(currentSegment, featureIndex, multiFeatureIndex, geometryIndex, segmentIndex) === false) return false; segmentIndex++; previousCoords = currentCoord; }) === false) return false; }); } /** * Callback for segmentReduce * * 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 segmentReduceCallback * @param {*} previousValue The accumulated value previously returned in the last invocation * of the callback, or initialValue, if supplied. * @param {Feature} currentSegment The current Segment 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. * @param {number} segmentIndex The current index of the Segment being processed. */ /** * Reduce 2-vertex line segment in any GeoJSON object, similar to Array.reduce() * (Multi)Point geometries do not contain segments therefore they are ignored during this operation. * * @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON * @param {Function} callback a method that takes (previousValue, currentSegment, currentIndex) * @param {*} [initialValue] Value to use as the first argument to the first call of the callback. * @returns {void} * @example * var polygon = turf.polygon([[[-50, 5], [-40, -10], [-50, -10], [-40, 5], [-50, 5]]]); * * // Iterate over GeoJSON by 2-vertex segments * turf.segmentReduce(polygon, function (previousSegment, currentSegment, featureIndex, multiFeatureIndex, geometryIndex, segmentIndex) { * //= previousSegment * //= currentSegment * //= featureIndex * //= multiFeatureIndex * //= geometryIndex * //= segmentInex * return currentSegment * }); * * // Calculate the total number of segments * var initialValue = 0 * var total = turf.segmentReduce(polygon, function (previousValue) { * previousValue++; * return previousValue; * }, initialValue); */ function segmentReduce(geojson, callback, initialValue) { var previousValue = initialValue; var started = false; segmentEach(geojson, function (currentSegment, featureIndex, multiFeatureIndex, geometryIndex, segmentIndex) { if (started === false && initialValue === undefined) previousValue = currentSegment; else previousValue = callback(previousValue, currentSegment, featureIndex, multiFeatureIndex, geometryIndex, segmentIndex); started = true; }); return previousValue; } /** * Callback for lineEach * * @callback lineEachCallback * @param {Feature} currentLine The current LineString|LinearRing 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 line or ring coordinates in LineString, Polygon, MultiLineString, MultiPolygon Features or Geometries, * similar to Array.forEach. * * @name lineEach * @param {Geometry|Feature} geojson object * @param {Function} callback a method that takes (currentLine, featureIndex, multiFeatureIndex, geometryIndex) * @example * var multiLine = turf.multiLineString([ * [[26, 37], [35, 45]], * [[36, 53], [38, 50], [41, 55]] * ]); * * turf.lineEach(multiLine, function (currentLine, featureIndex, multiFeatureIndex, geometryIndex) { * //=currentLine * //=featureIndex * //=multiFeatureIndex * //=geometryIndex * }); */ function lineEach(geojson, callback) { // validation if (!geojson) throw new Error('geojson is required'); flattenEach(geojson, function (feature$$1, featureIndex, multiFeatureIndex) { if (feature$$1.geometry === null) return; var type = feature$$1.geometry.type; var coords = feature$$1.geometry.coordinates; switch (type) { case 'LineString': if (callback(feature$$1, featureIndex, multiFeatureIndex, 0, 0) === false) return false; break; case 'Polygon': for (var geometryIndex = 0; geometryIndex < coords.length; geometryIndex++) { if (callback(lineString(coords[geometryIndex], feature$$1.properties), featureIndex, multiFeatureIndex, geometryIndex) === false) return false; } break; } }); } /** * Callback for lineReduce * * 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 lineReduceCallback * @param {*} previousValue The accumulated value previously returned in the last invocation * of the callback, or initialValue, if supplied. * @param {Feature} currentLine The current LineString|LinearRing 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 */ /** * Reduce features in any GeoJSON object, similar to Array.reduce(). * * @name lineReduce * @param {Geometry|Feature} geojson object * @param {Function} callback a method that takes (previousValue, currentLine, featureIndex, multiFeatureIndex, geometryIndex) * @param {*} [initialValue] Value to use as the first argument to the first call of the callback. * @returns {*} The value that results from the reduction. * @example * var multiPoly = turf.multiPolygon([ * turf.polygon([[[12,48],[2,41],[24,38],[12,48]], [[9,44],[13,41],[13,45],[9,44]]]), * turf.polygon([[[5, 5], [0, 0], [2, 2], [4, 4], [5, 5]]]) * ]); * * turf.lineReduce(multiPoly, function (previousValue, currentLine, featureIndex, multiFeatureIndex, geometryIndex) { * //=previousValue * //=currentLine * //=featureIndex * //=multiFeatureIndex * //=geometryIndex * return currentLine * }); */ function lineReduce(geojson, callback, initialValue) { var previousValue = initialValue; lineEach(geojson, function (currentLine, featureIndex, multiFeatureIndex, geometryIndex) { if (featureIndex === 0 && initialValue === undefined) previousValue = currentLine; else previousValue = callback(previousValue, currentLine, featureIndex, multiFeatureIndex, geometryIndex); }); return previousValue; } /** * Finds a particular 2-vertex LineString Segment from a GeoJSON using `@turf/meta` indexes. * * Negative indexes are permitted. * Point & MultiPoint will always return null. * * @param {FeatureCollection|Feature|Geometry} geojson Any GeoJSON Feature or Geometry * @param {Object} [options={}] Optional parameters * @param {number} [options.featureIndex=0] Feature Index * @param {number} [options.multiFeatureIndex=0] Multi-Feature Index * @param {number} [options.geometryIndex=0] Geometry Index * @param {number} [options.segmentIndex=0] Segment Index * @param {Object} [options.properties={}] Translate Properties to output LineString * @param {BBox} [options.bbox={}] Translate BBox to output LineString * @param {number|string} [options.id={}] Translate Id to output LineString * @returns {Feature} 2-vertex GeoJSON Feature LineString * @example * var multiLine = turf.multiLineString([ * [[10, 10], [50, 30], [30, 40]], * [[-10, -10], [-50, -30], [-30, -40]] * ]); * * // First Segment (defaults are 0) * turf.findSegment(multiLine); * // => Feature> * * // First Segment of 2nd Multi Feature * turf.findSegment(multiLine, {multiFeatureIndex: 1}); * // => Feature> * * // Last Segment of Last Multi Feature * turf.findSegment(multiLine, {multiFeatureIndex: -1, segmentIndex: -1}); * // => Feature> */ function findSegment(geojson, options) { // Optional Parameters options = options || {}; if (!isObject(options)) throw new Error('options is invalid'); var featureIndex = options.featureIndex || 0; var multiFeatureIndex = options.multiFeatureIndex || 0; var geometryIndex = options.geometryIndex || 0; var segmentIndex = options.segmentIndex || 0; // Find FeatureIndex var properties = options.properties; var geometry; switch (geojson.type) { case 'FeatureCollection': if (featureIndex < 0) featureIndex = geojson.features.length + featureIndex; properties = properties || geojson.features[featureIndex].properties; geometry = geojson.features[featureIndex].geometry; break; case 'Feature': properties = properties || geojson.properties; geometry = geojson.geometry; break; case 'Point': case 'MultiPoint': return null; case 'LineString': case 'Polygon': case 'MultiLineString': case 'MultiPolygon': geometry = geojson; break; default: throw new Error('geojson is invalid'); } // Find SegmentIndex if (geometry === null) return null; var coords = geometry.coordinates; switch (geometry.type) { case 'Point': case 'MultiPoint': return null; case 'LineString': if (segmentIndex < 0) segmentIndex = coords.length + segmentIndex - 1; return lineString([coords[segmentIndex], coords[segmentIndex + 1]], properties, options); case 'Polygon': if (geometryIndex < 0) geometryIndex = coords.length + geometryIndex; if (segmentIndex < 0) segmentIndex = coords[geometryIndex].length + segmentIndex - 1; return lineString([coords[geometryIndex][segmentIndex], coords[geometryIndex][segmentIndex + 1]], properties, options); case 'MultiLineString': if (multiFeatureIndex < 0) multiFeatureIndex = coords.length + multiFeatureIndex; if (segmentIndex < 0) segmentIndex = coords[multiFeatureIndex].length + segmentIndex - 1; return lineString([coords[multiFeatureIndex][segmentIndex], coords[multiFeatureIndex][segmentIndex + 1]], properties, options); case 'MultiPolygon': if (multiFeatureIndex < 0) multiFeatureIndex = coords.length + multiFeatureIndex; if (geometryIndex < 0) geometryIndex = coords[multiFeatureIndex].length + geometryIndex; if (segmentIndex < 0) segmentIndex = coords[multiFeatureIndex][geometryIndex].length - segmentIndex - 1; return lineString([coords[multiFeatureIndex][geometryIndex][segmentIndex], coords[multiFeatureIndex][geometryIndex][segmentIndex + 1]], properties, options); } throw new Error('geojson is invalid'); } /** * Finds a particular Point from a GeoJSON using `@turf/meta` indexes. * * Negative indexes are permitted. * * @param {FeatureCollection|Feature|Geometry} geojson Any GeoJSON Feature or Geometry * @param {Object} [options={}] Optional parameters * @param {number} [options.featureIndex=0] Feature Index * @param {number} [options.multiFeatureIndex=0] Multi-Feature Index * @param {number} [options.geometryIndex=0] Geometry Index * @param {number} [options.coordIndex=0] Coord Index * @param {Object} [options.properties={}] Translate Properties to output Point * @param {BBox} [options.bbox={}] Translate BBox to output Point * @param {number|string} [options.id={}] Translate Id to output Point * @returns {Feature} 2-vertex GeoJSON Feature Point * @example * var multiLine = turf.multiLineString([ * [[10, 10], [50, 30], [30, 40]], * [[-10, -10], [-50, -30], [-30, -40]] * ]); * * // First Segment (defaults are 0) * turf.findPoint(multiLine); * // => Feature> * * // First Segment of the 2nd Multi-Feature * turf.findPoint(multiLine, {multiFeatureIndex: 1}); * // => Feature> * * // Last Segment of last Multi-Feature * turf.findPoint(multiLine, {multiFeatureIndex: -1, coordIndex: -1}); * // => Feature> */ function findPoint(geojson, options) { // Optional Parameters options = options || {}; if (!isObject(options)) throw new Error('options is invalid'); var featureIndex = options.featureIndex || 0; var multiFeatureIndex = options.multiFeatureIndex || 0; var geometryIndex = options.geometryIndex || 0; var coordIndex = options.coordIndex || 0; // Find FeatureIndex var properties = options.properties; var geometry; switch (geojson.type) { case 'FeatureCollection': if (featureIndex < 0) featureIndex = geojson.features.length + featureIndex; properties = properties || geojson.features[featureIndex].properties; geometry = geojson.features[featureIndex].geometry; break; case 'Feature': properties = properties || geojson.properties; geometry = geojson.geometry; break; case 'Point': case 'MultiPoint': return null; case 'LineString': case 'Polygon': case 'MultiLineString': case 'MultiPolygon': geometry = geojson; break; default: throw new Error('geojson is invalid'); } // Find Coord Index if (geometry === null) return null; var coords = geometry.coordinates; switch (geometry.type) { case 'Point': return point(coords, properties, options); case 'MultiPoint': if (multiFeatureIndex < 0) multiFeatureIndex = coords.length + multiFeatureIndex; return point(coords[multiFeatureIndex], properties, options); case 'LineString': if (coordIndex < 0) coordIndex = coords.length + coordIndex; return point(coords[coordIndex], properties, options); case 'Polygon': if (geometryIndex < 0) geometryIndex = coords.length + geometryIndex; if (coordIndex < 0) coordIndex = coords[geometryIndex].length + coordIndex; return point(coords[geometryIndex][coordIndex], properties, options); case 'MultiLineString': if (multiFeatureIndex < 0) multiFeatureIndex = coords.length + multiFeatureIndex; if (coordIndex < 0) coordIndex = coords[multiFeatureIndex].length + coordIndex; return point(coords[multiFeatureIndex][coordIndex], properties, options); case 'MultiPolygon': if (multiFeatureIndex < 0) multiFeatureIndex = coords.length + multiFeatureIndex; if (geometryIndex < 0) geometryIndex = coords[multiFeatureIndex].length + geometryIndex; if (coordIndex < 0) coordIndex = coords[multiFeatureIndex][geometryIndex].length - coordIndex; return point(coords[multiFeatureIndex][geometryIndex][coordIndex], properties, options); } throw new Error('geojson is invalid'); } ;// CONCATENATED MODULE: ./node_modules/@turf/center/node_modules/@turf/bbox/main.es.js /** * 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 BBox = [Infinity, Infinity, -Infinity, -Infinity]; coordEach(geojson, function (coord) { if (BBox[0] > coord[0]) BBox[0] = coord[0]; if (BBox[1] > coord[1]) BBox[1] = coord[1]; if (BBox[2] < coord[0]) BBox[2] = coord[0]; if (BBox[3] < coord[1]) BBox[3] = coord[1]; }); return BBox; } /* harmony default export */ var bbox_main_es = (bbox); ;// CONCATENATED MODULE: ./node_modules/@turf/center/main.es.js /** * Takes a {@link Feature} or {@link FeatureCollection} and returns the absolute center point of all features. * * @name center * @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} a Point feature at the absolute center point of all input features * @example * var features = turf.featureCollection([ * turf.point( [-97.522259, 35.4691]), * turf.point( [-97.502754, 35.463455]), * turf.point( [-97.508269, 35.463245]) * ]); * * var center = turf.center(features); * * //addToMap * var addToMap = [features, center] * center.properties['marker-size'] = 'large'; * center.properties['marker-color'] = '#000'; */ function center(geojson, options) { // Optional parameters options = options || {}; if (!main_es_isObject(options)) throw new Error('options is invalid'); var properties = options.properties; // Input validation if (!geojson) throw new Error('geojson is required'); var ext = bbox_main_es(geojson); var x = (ext[0] + ext[2]) / 2; var y = (ext[1] + ext[3]) / 2; return main_es_point([x, y], properties); } /* harmony default export */ var center_main_es = (center); ;// CONCATENATED MODULE: ./node_modules/@turf/centroid/node_modules/@turf/helpers/main.es.js /** * Earth Radius used with the Harvesine formula and approximates using a spherical (non-ellipsoid) Earth. */ var main_es_earthRadius = 6371008.8; /** * Unit of measurement factors using a spherical (non-ellipsoid) earth radius. */ var main_es_factors = { meters: main_es_earthRadius, metres: main_es_earthRadius, millimeters: main_es_earthRadius * 1000, millimetres: main_es_earthRadius * 1000, centimeters: main_es_earthRadius * 100, centimetres: main_es_earthRadius * 100, kilometers: main_es_earthRadius / 1000, kilometres: main_es_earthRadius / 1000, miles: main_es_earthRadius / 1609.344, nauticalmiles: main_es_earthRadius / 1852, inches: main_es_earthRadius * 39.370, yards: main_es_earthRadius / 1.0936, feet: main_es_earthRadius * 3.28084, radians: 1, degrees: main_es_earthRadius / 111325, }; /** * Units of measurement factors based on 1 meter. */ var main_es_unitsFactors = { meters: 1, metres: 1, millimeters: 1000, millimetres: 1000, centimeters: 100, centimetres: 100, kilometers: 1 / 1000, kilometres: 1 / 1000, miles: 1 / 1609.344, nauticalmiles: 1 / 1852, inches: 39.370, yards: 1 / 1.0936, feet: 3.28084, radians: 1 / main_es_earthRadius, degrees: 1 / 111325, }; /** * Area of measurement factors based on 1 square meter. */ var main_es_areaFactors = { meters: 1, metres: 1, millimeters: 1000000, millimetres: 1000000, centimeters: 10000, centimetres: 10000, kilometers: 0.000001, kilometres: 0.000001, acres: 0.000247105, miles: 3.86e-7, yards: 1.195990046, feet: 10.763910417, inches: 1550.003100006 }; /** * 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} [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 helpers_main_es_feature(geometry, properties, options) { // Optional Parameters options = options || {}; if (!helpers_main_es_isObject(options)) throw new Error('options is invalid'); var bbox = options.bbox; var id = options.id; // Validation if (geometry === undefined) throw new Error('geometry is required'); if (properties && properties.constructor !== Object) throw new Error('properties must be an Object'); if (bbox) main_es_validateBBox(bbox); if (id) main_es_validateId(id); // Main var feat = {type: 'Feature'}; if (id) feat.id = id; if (bbox) feat.bbox = bbox; feat.properties = properties || {}; feat.geometry = geometry; return feat; } /** * 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} coordinates Coordinates * @param {Object} [options={}] Optional Parameters * @param {Array} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Geometry * @returns {Geometry} a GeoJSON Geometry * @example * var type = 'Point'; * var coordinates = [110, 50]; * * var geometry = turf.geometry(type, coordinates); * * //=geometry */ function main_es_geometry(type, coordinates, options) { // Optional Parameters options = options || {}; if (!helpers_main_es_isObject(options)) throw new Error('options is invalid'); var bbox = options.bbox; // Validation if (!type) throw new Error('type is required'); if (!coordinates) throw new Error('coordinates is required'); if (!Array.isArray(coordinates)) throw new Error('coordinates must be an Array'); if (bbox) main_es_validateBBox(bbox); // Main var geom; switch (type) { case 'Point': geom = helpers_main_es_point(coordinates).geometry; break; case 'LineString': geom = helpers_main_es_lineString(coordinates).geometry; break; case 'Polygon': geom = main_es_polygon(coordinates).geometry; break; case 'MultiPoint': geom = main_es_multiPoint(coordinates).geometry; break; case 'MultiLineString': geom = main_es_multiLineString(coordinates).geometry; break; case 'MultiPolygon': geom = main_es_multiPolygon(coordinates).geometry; break; default: throw new Error(type + ' is invalid'); } if (bbox) geom.bbox = bbox; return geom; } /** * Creates a {@link Point} {@link Feature} from a Position. * * @name point * @param {Array} 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} [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 Point feature * @example * var point = turf.point([-75.343, 39.984]); * * //=point */ function helpers_main_es_point(coordinates, properties, options) { if (!coordinates) throw new Error('coordinates is required'); if (!Array.isArray(coordinates)) throw new Error('coordinates must be an Array'); if (coordinates.length < 2) throw new Error('coordinates must be at least 2 numbers long'); if (!helpers_main_es_isNumber(coordinates[0]) || !helpers_main_es_isNumber(coordinates[1])) throw new Error('coordinates must contain numbers'); return helpers_main_es_feature({ type: 'Point', coordinates: coordinates }, properties, options); } /** * Creates a {@link Point} {@link FeatureCollection} from an Array of Point coordinates. * * @name points * @param {Array>} coordinates an array of Points * @param {Object} [properties={}] Translate these properties to each Feature * @param {Object} [options={}] Optional Parameters * @param {Array} [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 Feature * @example * var points = turf.points([ * [-75, 39], * [-80, 45], * [-78, 50] * ]); * * //=points */ function main_es_points(coordinates, properties, options) { if (!coordinates) throw new Error('coordinates is required'); if (!Array.isArray(coordinates)) throw new Error('coordinates must be an Array'); return main_es_featureCollection(coordinates.map(function (coords) { return helpers_main_es_point(coords, properties); }), options); } /** * Creates a {@link Polygon} {@link Feature} from an Array of LinearRings. * * @name polygon * @param {Array>>} 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} [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 Feature * @example * var polygon = turf.polygon([[[-5, 52], [-4, 56], [-2, 51], [-7, 54], [-5, 52]]], { name: 'poly1' }); * * //=polygon */ function main_es_polygon(coordinates, properties, options) { if (!coordinates) throw new Error('coordinates is required'); for (var i = 0; i < coordinates.length; i++) { var ring = coordinates[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 (i === 0 && j === 0 && !helpers_main_es_isNumber(ring[0][0]) || !helpers_main_es_isNumber(ring[0][1])) throw new Error('coordinates must contain numbers'); if (ring[ring.length - 1][j] !== ring[0][j]) { throw new Error('First and last Position are not equivalent.'); } } } return helpers_main_es_feature({ type: 'Polygon', coordinates: coordinates }, properties, options); } /** * Creates a {@link Polygon} {@link FeatureCollection} from an Array of Polygon coordinates. * * @name polygons * @param {Array>>>} 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} [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 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 main_es_polygons(coordinates, properties, options) { if (!coordinates) throw new Error('coordinates is required'); if (!Array.isArray(coordinates)) throw new Error('coordinates must be an Array'); return main_es_featureCollection(coordinates.map(function (coords) { return main_es_polygon(coords, properties); }), options); } /** * Creates a {@link LineString} {@link Feature} from an Array of Positions. * * @name lineString * @param {Array>} 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} [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 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 helpers_main_es_lineString(coordinates, properties, options) { if (!coordinates) throw new Error('coordinates is required'); if (coordinates.length < 2) throw new Error('coordinates must be an array of two or more positions'); // Check if first point of LineString contains two numbers if (!helpers_main_es_isNumber(coordinates[0][1]) || !helpers_main_es_isNumber(coordinates[0][1])) throw new Error('coordinates must contain numbers'); return helpers_main_es_feature({ type: 'LineString', coordinates: coordinates }, properties, options); } /** * Creates a {@link LineString} {@link FeatureCollection} from an Array of LineString coordinates. * * @name lineStrings * @param {Array>} 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} [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 FeatureCollection * @example * var linestrings = turf.lineStrings([ * [[-24, 63], [-23, 60], [-25, 65], [-20, 69]], * [[-14, 43], [-13, 40], [-15, 45], [-10, 49]] * ]); * * //=linestrings */ function main_es_lineStrings(coordinates, properties, options) { if (!coordinates) throw new Error('coordinates is required'); if (!Array.isArray(coordinates)) throw new Error('coordinates must be an Array'); return main_es_featureCollection(coordinates.map(function (coords) { return helpers_main_es_lineString(coords, properties); }), options); } /** * 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} [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 main_es_featureCollection(features, options) { // Optional Parameters options = options || {}; if (!helpers_main_es_isObject(options)) throw new Error('options is invalid'); var bbox = options.bbox; var id = options.id; // Validation if (!features) throw new Error('No features passed'); if (!Array.isArray(features)) throw new Error('features must be an Array'); if (bbox) main_es_validateBBox(bbox); if (id) main_es_validateId(id); // Main var fc = {type: 'FeatureCollection'}; if (id) fc.id = id; if (bbox) fc.bbox = bbox; fc.features = features; return fc; } /** * Creates a {@link Feature} based on a * coordinate array. Properties can be added optionally. * * @name multiLineString * @param {Array>>} 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} [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 MultiLineString feature * @throws {Error} if no coordinates are passed * @example * var multiLine = turf.multiLineString([[[0,0],[10,10]]]); * * //=multiLine */ function main_es_multiLineString(coordinates, properties, options) { if (!coordinates) throw new Error('coordinates is required'); return helpers_main_es_feature({ type: 'MultiLineString', coordinates: coordinates }, properties, options); } /** * Creates a {@link Feature} based on a * coordinate array. Properties can be added optionally. * * @name multiPoint * @param {Array>} 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} [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 MultiPoint feature * @throws {Error} if no coordinates are passed * @example * var multiPt = turf.multiPoint([[0,0],[10,10]]); * * //=multiPt */ function main_es_multiPoint(coordinates, properties, options) { if (!coordinates) throw new Error('coordinates is required'); return helpers_main_es_feature({ type: 'MultiPoint', coordinates: coordinates }, properties, options); } /** * Creates a {@link Feature} based on a * coordinate array. Properties can be added optionally. * * @name multiPolygon * @param {Array>>>} 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} [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 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 main_es_multiPolygon(coordinates, properties, options) { if (!coordinates) throw new Error('coordinates is required'); return helpers_main_es_feature({ type: 'MultiPolygon', coordinates: coordinates }, properties, options); } /** * Creates a {@link Feature} based on a * coordinate array. Properties can be added optionally. * * @name geometryCollection * @param {Array} 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} [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 GeometryCollection Feature * @example * var pt = { * "type": "Point", * "coordinates": [100, 0] * }; * var line = { * "type": "LineString", * "coordinates": [ [101, 0], [102, 1] ] * }; * var collection = turf.geometryCollection([pt, line]); * * //=collection */ function main_es_geometryCollection(geometries, properties, options) { if (!geometries) throw new Error('geometries is required'); if (!Array.isArray(geometries)) throw new Error('geometries must be an Array'); return helpers_main_es_feature({ type: 'GeometryCollection', geometries: geometries }, properties, options); } /** * 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 main_es_round(num, precision) { if (num === undefined || num === null || isNaN(num)) throw new Error('num is required'); 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; } /** * 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 main_es_radiansToLength(radians, units) { if (radians === undefined || radians === null) throw new Error('radians is required'); if (units && typeof units !== 'string') throw new Error('units must be a string'); var factor = main_es_factors[units || 'kilometers']; if (!factor) throw new Error(units + ' units is invalid'); return radians * factor; } /** * 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 main_es_lengthToRadians(distance, units) { if (distance === undefined || distance === null) throw new Error('distance is required'); if (units && typeof units !== 'string') throw new Error('units must be a string'); var factor = main_es_factors[units || 'kilometers']; if (!factor) throw new Error(units + ' units is invalid'); return distance / factor; } /** * 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 main_es_lengthToDegrees(distance, units) { return main_es_radiansToDegrees(main_es_lengthToRadians(distance, units)); } /** * 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 main_es_bearingToAzimuth(bearing) { if (bearing === null || bearing === undefined) throw new Error('bearing is required'); var angle = bearing % 360; if (angle < 0) angle += 360; return angle; } /** * Converts an angle in radians to degrees * * @name radiansToDegrees * @param {number} radians angle in radians * @returns {number} degrees between 0 and 360 degrees */ function main_es_radiansToDegrees(radians) { if (radians === null || radians === undefined) throw new Error('radians is required'); var degrees = radians % (2 * Math.PI); return degrees * 180 / Math.PI; } /** * Converts an angle in degrees to radians * * @name degreesToRadians * @param {number} degrees angle between 0 and 360 degrees * @returns {number} angle in radians */ function main_es_degreesToRadians(degrees) { if (degrees === null || degrees === undefined) throw new Error('degrees is required'); var radians = degrees % 360; return radians * Math.PI / 180; } /** * 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 {string} originalUnit of the length * @param {string} [finalUnit='kilometers'] returned unit * @returns {number} the converted length */ function main_es_convertLength(length, originalUnit, finalUnit) { if (length === null || length === undefined) throw new Error('length is required'); if (!(length >= 0)) throw new Error('length must be a positive number'); return main_es_radiansToLength(main_es_lengthToRadians(length, originalUnit), finalUnit || 'kilometers'); } /** * 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 {string} [originalUnit='meters'] of the distance * @param {string} [finalUnit='kilometers'] returned unit * @returns {number} the converted distance */ function main_es_convertArea(area, originalUnit, finalUnit) { if (area === null || area === undefined) throw new Error('area is required'); if (!(area >= 0)) throw new Error('area must be a positive number'); var startFactor = main_es_areaFactors[originalUnit || 'meters']; if (!startFactor) throw new Error('invalid original units'); var finalFactor = main_es_areaFactors[finalUnit || 'kilometers']; if (!finalFactor) throw new Error('invalid final units'); return (area / startFactor) * finalFactor; } /** * isNumber * * @param {*} num Number to validate * @returns {boolean} true/false * @example * turf.isNumber(123) * //=true * turf.isNumber('foo') * //=false */ function helpers_main_es_isNumber(num) { return !isNaN(num) && num !== null && !Array.isArray(num); } /** * isObject * * @param {*} input variable to validate * @returns {boolean} true/false * @example * turf.isObject({elevation: 10}) * //=true * turf.isObject('foo') * //=false */ function helpers_main_es_isObject(input) { return (!!input) && (input.constructor === Object); } /** * Validate BBox * * @private * @param {Array} 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 main_es_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 (!helpers_main_es_isNumber(num)) throw new Error('bbox must only contain numbers'); }); } /** * 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 main_es_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'); } // Deprecated methods function main_es_radians2degrees() { throw new Error('method has been renamed to `radiansToDegrees`'); } function main_es_degrees2radians() { throw new Error('method has been renamed to `degreesToRadians`'); } function main_es_distanceToDegrees() { throw new Error('method has been renamed to `lengthToDegrees`'); } function main_es_distanceToRadians() { throw new Error('method has been renamed to `lengthToRadians`'); } function main_es_radiansToDistance() { throw new Error('method has been renamed to `radiansToLength`'); } function main_es_bearingToAngle() { throw new Error('method has been renamed to `bearingToAzimuth`'); } function main_es_convertDistance() { throw new Error('method has been renamed to `convertLength`'); } ;// CONCATENATED MODULE: ./node_modules/@turf/centroid/node_modules/@turf/meta/main.es.js /** * Callback for coordEach * * @callback coordEachCallback * @param {Array} 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 main_es_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++) { if (geomType === 'MultiPolygon') 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 (main_es_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} 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 main_es_coordReduce(geojson, callback, initialValue, excludeWrapCoord) { var previousValue = initialValue; main_es_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 main_es_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|Feature} geojson any GeoJSON object * @param {Function} callback a method that takes (previousValue, currentProperties, featureIndex) * @param {*} [initialValue] Value to use as the first argument to the first call of the callback. * @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.propReduce(features, function (previousValue, currentProperties, featureIndex) { * //=previousValue * //=currentProperties * //=featureIndex * return currentProperties * }); */ function main_es_propReduce(geojson, callback, initialValue) { var previousValue = initialValue; main_es_propEach(geojson, function (currentProperties, featureIndex) { if (featureIndex === 0 && initialValue === undefined) previousValue = currentProperties; else previousValue = callback(previousValue, currentProperties, featureIndex); }); return previousValue; } /** * Callback for featureEach * * @callback featureEachCallback * @param {Feature} currentFeature The current Feature being processed. * @param {number} featureIndex The current index of the Feature being processed. */ /** * Iterate over features in any GeoJSON object, similar to * Array.forEach. * * @name featureEach * @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON object * @param {Function} callback a method that takes (currentFeature, featureIndex) * @returns {void} * @example * var features = turf.featureCollection([ * turf.point([26, 37], {foo: 'bar'}), * turf.point([36, 53], {hello: 'world'}) * ]); * * turf.featureEach(features, function (currentFeature, featureIndex) { * //=currentFeature * //=featureIndex * }); */ function main_es_featureEach(geojson, callback) { if (geojson.type === 'Feature') { callback(geojson, 0); } else if (geojson.type === 'FeatureCollection') { for (var i = 0; i < geojson.features.length; i++) { if (callback(geojson.features[i], i) === false) break; } } } /** * Callback for featureReduce * * 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 featureReduceCallback * @param {*} previousValue The accumulated value previously returned in the last invocation * of the callback, or initialValue, if supplied. * @param {Feature} currentFeature The current Feature being processed. * @param {number} featureIndex The current index of the Feature being processed. */ /** * Reduce features in any GeoJSON object, similar to Array.reduce(). * * @name featureReduce * @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON object * @param {Function} callback a method that takes (previousValue, currentFeature, featureIndex) * @param {*} [initialValue] Value to use as the first argument to the first call of the callback. * @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.featureReduce(features, function (previousValue, currentFeature, featureIndex) { * //=previousValue * //=currentFeature * //=featureIndex * return currentFeature * }); */ function main_es_featureReduce(geojson, callback, initialValue) { var previousValue = initialValue; main_es_featureEach(geojson, function (currentFeature, featureIndex) { if (featureIndex === 0 && initialValue === undefined) previousValue = currentFeature; else previousValue = callback(previousValue, currentFeature, featureIndex); }); return previousValue; } /** * Get all coordinates from any GeoJSON object. * * @name coordAll * @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON object * @returns {Array>} coordinate position array * @example * var features = turf.featureCollection([ * turf.point([26, 37], {foo: 'bar'}), * turf.point([36, 53], {hello: 'world'}) * ]); * * var coords = turf.coordAll(features); * //= [[26, 37], [36, 53]] */ function main_es_coordAll(geojson) { var coords = []; main_es_coordEach(geojson, function (coord) { coords.push(coord); }); return coords; } /** * Callback for geomEach * * @callback geomEachCallback * @param {Geometry} currentGeometry The current Geometry being processed. * @param {number} featureIndex The current index of the Feature being processed. * @param {Object} featureProperties The current Feature Properties being processed. * @param {Array} featureBBox The current Feature BBox being processed. * @param {number|string} featureId The current Feature Id being processed. */ /** * Iterate over each geometry in any GeoJSON object, similar to Array.forEach() * * @name geomEach * @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON object * @param {Function} callback a method that takes (currentGeometry, featureIndex, featureProperties, featureBBox, featureId) * @returns {void} * @example * var features = turf.featureCollection([ * turf.point([26, 37], {foo: 'bar'}), * turf.point([36, 53], {hello: 'world'}) * ]); * * turf.geomEach(features, function (currentGeometry, featureIndex, featureProperties, featureBBox, featureId) { * //=currentGeometry * //=featureIndex * //=featureProperties * //=featureBBox * //=featureId * }); */ function main_es_geomEach(geojson, callback) { var i, j, g, geometry, stopG, geometryMaybeCollection, isGeometryCollection, featureProperties, featureBBox, featureId, featureIndex = 0, isFeatureCollection = geojson.type === 'FeatureCollection', isFeature = geojson.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 (i = 0; i < stop; i++) { geometryMaybeCollection = (isFeatureCollection ? geojson.features[i].geometry : (isFeature ? geojson.geometry : geojson)); featureProperties = (isFeatureCollection ? geojson.features[i].properties : (isFeature ? geojson.properties : {})); featureBBox = (isFeatureCollection ? geojson.features[i].bbox : (isFeature ? geojson.bbox : undefined)); featureId = (isFeatureCollection ? geojson.features[i].id : (isFeature ? geojson.id : undefined)); isGeometryCollection = (geometryMaybeCollection) ? geometryMaybeCollection.type === 'GeometryCollection' : false; stopG = isGeometryCollection ? geometryMaybeCollection.geometries.length : 1; for (g = 0; g < stopG; g++) { geometry = isGeometryCollection ? geometryMaybeCollection.geometries[g] : geometryMaybeCollection; // Handle null Geometry if (geometry === null) { if (callback(null, featureIndex, featureProperties, featureBBox, featureId) === false) return false; continue; } switch (geometry.type) { case 'Point': case 'LineString': case 'MultiPoint': case 'Polygon': case 'MultiLineString': case 'MultiPolygon': { if (callback(geometry, featureIndex, featureProperties, featureBBox, featureId) === false) return false; break; } case 'GeometryCollection': { for (j = 0; j < geometry.geometries.length; j++) { if (callback(geometry.geometries[j], featureIndex, featureProperties, featureBBox, featureId) === false) return false; } break; } default: throw new Error('Unknown Geometry Type'); } } // Only increase `featureIndex` per each feature featureIndex++; } } /** * Callback for geomReduce * * 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 geomReduceCallback * @param {*} previousValue The accumulated value previously returned in the last invocation * of the callback, or initialValue, if supplied. * @param {Geometry} currentGeometry The current Geometry being processed. * @param {number} featureIndex The current index of the Feature being processed. * @param {Object} featureProperties The current Feature Properties being processed. * @param {Array} featureBBox The current Feature BBox being processed. * @param {number|string} featureId The current Feature Id being processed. */ /** * Reduce geometry in any GeoJSON object, similar to Array.reduce(). * * @name geomReduce * @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON object * @param {Function} callback a method that takes (previousValue, currentGeometry, featureIndex, featureProperties, featureBBox, featureId) * @param {*} [initialValue] Value to use as the first argument to the first call of the callback. * @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.geomReduce(features, function (previousValue, currentGeometry, featureIndex, featureProperties, featureBBox, featureId) { * //=previousValue * //=currentGeometry * //=featureIndex * //=featureProperties * //=featureBBox * //=featureId * return currentGeometry * }); */ function main_es_geomReduce(geojson, callback, initialValue) { var previousValue = initialValue; main_es_geomEach(geojson, function (currentGeometry, featureIndex, featureProperties, featureBBox, featureId) { if (featureIndex === 0 && initialValue === undefined) previousValue = currentGeometry; else previousValue = callback(previousValue, currentGeometry, featureIndex, featureProperties, featureBBox, featureId); }); return previousValue; } /** * Callback for flattenEach * * @callback flattenEachCallback * @param {Feature} currentFeature The current flattened feature 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. */ /** * Iterate over flattened features in any GeoJSON object, similar to * Array.forEach. * * @name flattenEach * @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON object * @param {Function} callback a method that takes (currentFeature, featureIndex, multiFeatureIndex) * @example * var features = turf.featureCollection([ * turf.point([26, 37], {foo: 'bar'}), * turf.multiPoint([[40, 30], [36, 53]], {hello: 'world'}) * ]); * * turf.flattenEach(features, function (currentFeature, featureIndex, multiFeatureIndex) { * //=currentFeature * //=featureIndex * //=multiFeatureIndex * }); */ function main_es_flattenEach(geojson, callback) { main_es_geomEach(geojson, function (geometry, featureIndex, properties, bbox, id) { // Callback for single geometry var type = (geometry === null) ? null : geometry.type; switch (type) { case null: case 'Point': case 'LineString': case 'Polygon': if (callback(feature(geometry, properties, {bbox: bbox, id: id}), featureIndex, 0) === false) return false; return; } var geomType; // Callback for multi-geometry switch (type) { case 'MultiPoint': geomType = 'Point'; break; case 'MultiLineString': geomType = 'LineString'; break; case 'MultiPolygon': geomType = 'Polygon'; break; } for (var multiFeatureIndex = 0; multiFeatureIndex < geometry.coordinates.length; multiFeatureIndex++) { var coordinate = geometry.coordinates[multiFeatureIndex]; var geom = { type: geomType, coordinates: coordinate }; if (callback(feature(geom, properties), featureIndex, multiFeatureIndex) === false) return false; } }); } /** * Callback for flattenReduce * * 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 flattenReduceCallback * @param {*} previousValue The accumulated value previously returned in the last invocation * of the callback, or initialValue, if supplied. * @param {Feature} currentFeature The current Feature 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. */ /** * Reduce flattened features in any GeoJSON object, similar to Array.reduce(). * * @name flattenReduce * @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON object * @param {Function} callback a method that takes (previousValue, currentFeature, featureIndex, multiFeatureIndex) * @param {*} [initialValue] Value to use as the first argument to the first call of the callback. * @returns {*} The value that results from the reduction. * @example * var features = turf.featureCollection([ * turf.point([26, 37], {foo: 'bar'}), * turf.multiPoint([[40, 30], [36, 53]], {hello: 'world'}) * ]); * * turf.flattenReduce(features, function (previousValue, currentFeature, featureIndex, multiFeatureIndex) { * //=previousValue * //=currentFeature * //=featureIndex * //=multiFeatureIndex * return currentFeature * }); */ function main_es_flattenReduce(geojson, callback, initialValue) { var previousValue = initialValue; main_es_flattenEach(geojson, function (currentFeature, featureIndex, multiFeatureIndex) { if (featureIndex === 0 && multiFeatureIndex === 0 && initialValue === undefined) previousValue = currentFeature; else previousValue = callback(previousValue, currentFeature, featureIndex, multiFeatureIndex); }); return previousValue; } /** * Callback for segmentEach * * @callback segmentEachCallback * @param {Feature} currentSegment The current Segment 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. * @param {number} segmentIndex The current index of the Segment being processed. * @returns {void} */ /** * Iterate over 2-vertex line segment in any GeoJSON object, similar to Array.forEach() * (Multi)Point geometries do not contain segments therefore they are ignored during this operation. * * @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON * @param {Function} callback a method that takes (currentSegment, featureIndex, multiFeatureIndex, geometryIndex, segmentIndex) * @returns {void} * @example * var polygon = turf.polygon([[[-50, 5], [-40, -10], [-50, -10], [-40, 5], [-50, 5]]]); * * // Iterate over GeoJSON by 2-vertex segments * turf.segmentEach(polygon, function (currentSegment, featureIndex, multiFeatureIndex, geometryIndex, segmentIndex) { * //=currentSegment * //=featureIndex * //=multiFeatureIndex * //=geometryIndex * //=segmentIndex * }); * * // Calculate the total number of segments * var total = 0; * turf.segmentEach(polygon, function () { * total++; * }); */ function main_es_segmentEach(geojson, callback) { main_es_flattenEach(geojson, function (feature$$1, featureIndex, multiFeatureIndex) { var segmentIndex = 0; // Exclude null Geometries if (!feature$$1.geometry) return; // (Multi)Point geometries do not contain segments therefore they are ignored during this operation. var type = feature$$1.geometry.type; if (type === 'Point' || type === 'MultiPoint') return; // Generate 2-vertex line segments var previousCoords; if (main_es_coordEach(feature$$1, function (currentCoord, coordIndex, featureIndexCoord, mutliPartIndexCoord, geometryIndex) { // Simulating a meta.coordReduce() since `reduce` operations cannot be stopped by returning `false` if (previousCoords === undefined) { previousCoords = currentCoord; return; } var currentSegment = lineString([previousCoords, currentCoord], feature$$1.properties); if (callback(currentSegment, featureIndex, multiFeatureIndex, geometryIndex, segmentIndex) === false) return false; segmentIndex++; previousCoords = currentCoord; }) === false) return false; }); } /** * Callback for segmentReduce * * 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 segmentReduceCallback * @param {*} previousValue The accumulated value previously returned in the last invocation * of the callback, or initialValue, if supplied. * @param {Feature} currentSegment The current Segment 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. * @param {number} segmentIndex The current index of the Segment being processed. */ /** * Reduce 2-vertex line segment in any GeoJSON object, similar to Array.reduce() * (Multi)Point geometries do not contain segments therefore they are ignored during this operation. * * @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON * @param {Function} callback a method that takes (previousValue, currentSegment, currentIndex) * @param {*} [initialValue] Value to use as the first argument to the first call of the callback. * @returns {void} * @example * var polygon = turf.polygon([[[-50, 5], [-40, -10], [-50, -10], [-40, 5], [-50, 5]]]); * * // Iterate over GeoJSON by 2-vertex segments * turf.segmentReduce(polygon, function (previousSegment, currentSegment, featureIndex, multiFeatureIndex, geometryIndex, segmentIndex) { * //= previousSegment * //= currentSegment * //= featureIndex * //= multiFeatureIndex * //= geometryIndex * //= segmentInex * return currentSegment * }); * * // Calculate the total number of segments * var initialValue = 0 * var total = turf.segmentReduce(polygon, function (previousValue) { * previousValue++; * return previousValue; * }, initialValue); */ function main_es_segmentReduce(geojson, callback, initialValue) { var previousValue = initialValue; var started = false; main_es_segmentEach(geojson, function (currentSegment, featureIndex, multiFeatureIndex, geometryIndex, segmentIndex) { if (started === false && initialValue === undefined) previousValue = currentSegment; else previousValue = callback(previousValue, currentSegment, featureIndex, multiFeatureIndex, geometryIndex, segmentIndex); started = true; }); return previousValue; } /** * Callback for lineEach * * @callback lineEachCallback * @param {Feature} currentLine The current LineString|LinearRing 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 line or ring coordinates in LineString, Polygon, MultiLineString, MultiPolygon Features or Geometries, * similar to Array.forEach. * * @name lineEach * @param {Geometry|Feature} geojson object * @param {Function} callback a method that takes (currentLine, featureIndex, multiFeatureIndex, geometryIndex) * @example * var multiLine = turf.multiLineString([ * [[26, 37], [35, 45]], * [[36, 53], [38, 50], [41, 55]] * ]); * * turf.lineEach(multiLine, function (currentLine, featureIndex, multiFeatureIndex, geometryIndex) { * //=currentLine * //=featureIndex * //=multiFeatureIndex * //=geometryIndex * }); */ function main_es_lineEach(geojson, callback) { // validation if (!geojson) throw new Error('geojson is required'); main_es_flattenEach(geojson, function (feature$$1, featureIndex, multiFeatureIndex) { if (feature$$1.geometry === null) return; var type = feature$$1.geometry.type; var coords = feature$$1.geometry.coordinates; switch (type) { case 'LineString': if (callback(feature$$1, featureIndex, multiFeatureIndex, 0, 0) === false) return false; break; case 'Polygon': for (var geometryIndex = 0; geometryIndex < coords.length; geometryIndex++) { if (callback(lineString(coords[geometryIndex], feature$$1.properties), featureIndex, multiFeatureIndex, geometryIndex) === false) return false; } break; } }); } /** * Callback for lineReduce * * 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 lineReduceCallback * @param {*} previousValue The accumulated value previously returned in the last invocation * of the callback, or initialValue, if supplied. * @param {Feature} currentLine The current LineString|LinearRing 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 */ /** * Reduce features in any GeoJSON object, similar to Array.reduce(). * * @name lineReduce * @param {Geometry|Feature} geojson object * @param {Function} callback a method that takes (previousValue, currentLine, featureIndex, multiFeatureIndex, geometryIndex) * @param {*} [initialValue] Value to use as the first argument to the first call of the callback. * @returns {*} The value that results from the reduction. * @example * var multiPoly = turf.multiPolygon([ * turf.polygon([[[12,48],[2,41],[24,38],[12,48]], [[9,44],[13,41],[13,45],[9,44]]]), * turf.polygon([[[5, 5], [0, 0], [2, 2], [4, 4], [5, 5]]]) * ]); * * turf.lineReduce(multiPoly, function (previousValue, currentLine, featureIndex, multiFeatureIndex, geometryIndex) { * //=previousValue * //=currentLine * //=featureIndex * //=multiFeatureIndex * //=geometryIndex * return currentLine * }); */ function main_es_lineReduce(geojson, callback, initialValue) { var previousValue = initialValue; main_es_lineEach(geojson, function (currentLine, featureIndex, multiFeatureIndex, geometryIndex) { if (featureIndex === 0 && initialValue === undefined) previousValue = currentLine; else previousValue = callback(previousValue, currentLine, featureIndex, multiFeatureIndex, geometryIndex); }); return previousValue; } /** * Finds a particular 2-vertex LineString Segment from a GeoJSON using `@turf/meta` indexes. * * Negative indexes are permitted. * Point & MultiPoint will always return null. * * @param {FeatureCollection|Feature|Geometry} geojson Any GeoJSON Feature or Geometry * @param {Object} [options={}] Optional parameters * @param {number} [options.featureIndex=0] Feature Index * @param {number} [options.multiFeatureIndex=0] Multi-Feature Index * @param {number} [options.geometryIndex=0] Geometry Index * @param {number} [options.segmentIndex=0] Segment Index * @param {Object} [options.properties={}] Translate Properties to output LineString * @param {BBox} [options.bbox={}] Translate BBox to output LineString * @param {number|string} [options.id={}] Translate Id to output LineString * @returns {Feature} 2-vertex GeoJSON Feature LineString * @example * var multiLine = turf.multiLineString([ * [[10, 10], [50, 30], [30, 40]], * [[-10, -10], [-50, -30], [-30, -40]] * ]); * * // First Segment (defaults are 0) * turf.findSegment(multiLine); * // => Feature> * * // First Segment of 2nd Multi Feature * turf.findSegment(multiLine, {multiFeatureIndex: 1}); * // => Feature> * * // Last Segment of Last Multi Feature * turf.findSegment(multiLine, {multiFeatureIndex: -1, segmentIndex: -1}); * // => Feature> */ function main_es_findSegment(geojson, options) { // Optional Parameters options = options || {}; if (!isObject(options)) throw new Error('options is invalid'); var featureIndex = options.featureIndex || 0; var multiFeatureIndex = options.multiFeatureIndex || 0; var geometryIndex = options.geometryIndex || 0; var segmentIndex = options.segmentIndex || 0; // Find FeatureIndex var properties = options.properties; var geometry; switch (geojson.type) { case 'FeatureCollection': if (featureIndex < 0) featureIndex = geojson.features.length + featureIndex; properties = properties || geojson.features[featureIndex].properties; geometry = geojson.features[featureIndex].geometry; break; case 'Feature': properties = properties || geojson.properties; geometry = geojson.geometry; break; case 'Point': case 'MultiPoint': return null; case 'LineString': case 'Polygon': case 'MultiLineString': case 'MultiPolygon': geometry = geojson; break; default: throw new Error('geojson is invalid'); } // Find SegmentIndex if (geometry === null) return null; var coords = geometry.coordinates; switch (geometry.type) { case 'Point': case 'MultiPoint': return null; case 'LineString': if (segmentIndex < 0) segmentIndex = coords.length + segmentIndex - 1; return lineString([coords[segmentIndex], coords[segmentIndex + 1]], properties, options); case 'Polygon': if (geometryIndex < 0) geometryIndex = coords.length + geometryIndex; if (segmentIndex < 0) segmentIndex = coords[geometryIndex].length + segmentIndex - 1; return lineString([coords[geometryIndex][segmentIndex], coords[geometryIndex][segmentIndex + 1]], properties, options); case 'MultiLineString': if (multiFeatureIndex < 0) multiFeatureIndex = coords.length + multiFeatureIndex; if (segmentIndex < 0) segmentIndex = coords[multiFeatureIndex].length + segmentIndex - 1; return lineString([coords[multiFeatureIndex][segmentIndex], coords[multiFeatureIndex][segmentIndex + 1]], properties, options); case 'MultiPolygon': if (multiFeatureIndex < 0) multiFeatureIndex = coords.length + multiFeatureIndex; if (geometryIndex < 0) geometryIndex = coords[multiFeatureIndex].length + geometryIndex; if (segmentIndex < 0) segmentIndex = coords[multiFeatureIndex][geometryIndex].length - segmentIndex - 1; return lineString([coords[multiFeatureIndex][geometryIndex][segmentIndex], coords[multiFeatureIndex][geometryIndex][segmentIndex + 1]], properties, options); } throw new Error('geojson is invalid'); } /** * Finds a particular Point from a GeoJSON using `@turf/meta` indexes. * * Negative indexes are permitted. * * @param {FeatureCollection|Feature|Geometry} geojson Any GeoJSON Feature or Geometry * @param {Object} [options={}] Optional parameters * @param {number} [options.featureIndex=0] Feature Index * @param {number} [options.multiFeatureIndex=0] Multi-Feature Index * @param {number} [options.geometryIndex=0] Geometry Index * @param {number} [options.coordIndex=0] Coord Index * @param {Object} [options.properties={}] Translate Properties to output Point * @param {BBox} [options.bbox={}] Translate BBox to output Point * @param {number|string} [options.id={}] Translate Id to output Point * @returns {Feature} 2-vertex GeoJSON Feature Point * @example * var multiLine = turf.multiLineString([ * [[10, 10], [50, 30], [30, 40]], * [[-10, -10], [-50, -30], [-30, -40]] * ]); * * // First Segment (defaults are 0) * turf.findPoint(multiLine); * // => Feature> * * // First Segment of the 2nd Multi-Feature * turf.findPoint(multiLine, {multiFeatureIndex: 1}); * // => Feature> * * // Last Segment of last Multi-Feature * turf.findPoint(multiLine, {multiFeatureIndex: -1, coordIndex: -1}); * // => Feature> */ function main_es_findPoint(geojson, options) { // Optional Parameters options = options || {}; if (!isObject(options)) throw new Error('options is invalid'); var featureIndex = options.featureIndex || 0; var multiFeatureIndex = options.multiFeatureIndex || 0; var geometryIndex = options.geometryIndex || 0; var coordIndex = options.coordIndex || 0; // Find FeatureIndex var properties = options.properties; var geometry; switch (geojson.type) { case 'FeatureCollection': if (featureIndex < 0) featureIndex = geojson.features.length + featureIndex; properties = properties || geojson.features[featureIndex].properties; geometry = geojson.features[featureIndex].geometry; break; case 'Feature': properties = properties || geojson.properties; geometry = geojson.geometry; break; case 'Point': case 'MultiPoint': return null; case 'LineString': case 'Polygon': case 'MultiLineString': case 'MultiPolygon': geometry = geojson; break; default: throw new Error('geojson is invalid'); } // Find Coord Index if (geometry === null) return null; var coords = geometry.coordinates; switch (geometry.type) { case 'Point': return point(coords, properties, options); case 'MultiPoint': if (multiFeatureIndex < 0) multiFeatureIndex = coords.length + multiFeatureIndex; return point(coords[multiFeatureIndex], properties, options); case 'LineString': if (coordIndex < 0) coordIndex = coords.length + coordIndex; return point(coords[coordIndex], properties, options); case 'Polygon': if (geometryIndex < 0) geometryIndex = coords.length + geometryIndex; if (coordIndex < 0) coordIndex = coords[geometryIndex].length + coordIndex; return point(coords[geometryIndex][coordIndex], properties, options); case 'MultiLineString': if (multiFeatureIndex < 0) multiFeatureIndex = coords.length + multiFeatureIndex; if (coordIndex < 0) coordIndex = coords[multiFeatureIndex].length + coordIndex; return point(coords[multiFeatureIndex][coordIndex], properties, options); case 'MultiPolygon': if (multiFeatureIndex < 0) multiFeatureIndex = coords.length + multiFeatureIndex; if (geometryIndex < 0) geometryIndex = coords[multiFeatureIndex].length + geometryIndex; if (coordIndex < 0) coordIndex = coords[multiFeatureIndex][geometryIndex].length - coordIndex; return point(coords[multiFeatureIndex][geometryIndex][coordIndex], properties, options); } throw new Error('geojson is invalid'); } ;// CONCATENATED MODULE: ./node_modules/@turf/centroid/main.es.js /** * 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} [properties={}] an Object that is used as the {@link Feature}'s properties * @returns {Feature} 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, properties) { var xSum = 0; var ySum = 0; var len = 0; main_es_coordEach(geojson, function (coord) { xSum += coord[0]; ySum += coord[1]; len++; }, true); return helpers_main_es_point([xSum / len, ySum / len], properties); } /* harmony default export */ var centroid_main_es = (centroid); ;// CONCATENATED MODULE: ./node_modules/@turf/transform-scale/node_modules/@turf/helpers/main.es.js /** * Earth Radius used with the Harvesine formula and approximates using a spherical (non-ellipsoid) Earth. */ var helpers_main_es_earthRadius = 6371008.8; /** * Unit of measurement factors using a spherical (non-ellipsoid) earth radius. */ var helpers_main_es_factors = { meters: helpers_main_es_earthRadius, metres: helpers_main_es_earthRadius, millimeters: helpers_main_es_earthRadius * 1000, millimetres: helpers_main_es_earthRadius * 1000, centimeters: helpers_main_es_earthRadius * 100, centimetres: helpers_main_es_earthRadius * 100, kilometers: helpers_main_es_earthRadius / 1000, kilometres: helpers_main_es_earthRadius / 1000, miles: helpers_main_es_earthRadius / 1609.344, nauticalmiles: helpers_main_es_earthRadius / 1852, inches: helpers_main_es_earthRadius * 39.370, yards: helpers_main_es_earthRadius / 1.0936, feet: helpers_main_es_earthRadius * 3.28084, radians: 1, degrees: helpers_main_es_earthRadius / 111325, }; /** * Units of measurement factors based on 1 meter. */ var helpers_main_es_unitsFactors = { meters: 1, metres: 1, millimeters: 1000, millimetres: 1000, centimeters: 100, centimetres: 100, kilometers: 1 / 1000, kilometres: 1 / 1000, miles: 1 / 1609.344, nauticalmiles: 1 / 1852, inches: 39.370, yards: 1 / 1.0936, feet: 3.28084, radians: 1 / helpers_main_es_earthRadius, degrees: 1 / 111325, }; /** * Area of measurement factors based on 1 square meter. */ var helpers_main_es_areaFactors = { meters: 1, metres: 1, millimeters: 1000000, millimetres: 1000000, centimeters: 10000, centimetres: 10000, kilometers: 0.000001, kilometres: 0.000001, acres: 0.000247105, miles: 3.86e-7, yards: 1.195990046, feet: 10.763910417, inches: 1550.003100006 }; /** * 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} [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 _turf_helpers_main_es_feature(geometry, properties, options) { // Optional Parameters options = options || {}; if (!_turf_helpers_main_es_isObject(options)) throw new Error('options is invalid'); var bbox = options.bbox; var id = options.id; // Validation if (geometry === undefined) throw new Error('geometry is required'); if (properties && properties.constructor !== Object) throw new Error('properties must be an Object'); if (bbox) helpers_main_es_validateBBox(bbox); if (id) helpers_main_es_validateId(id); // Main var feat = {type: 'Feature'}; if (id) feat.id = id; if (bbox) feat.bbox = bbox; feat.properties = properties || {}; feat.geometry = geometry; return feat; } /** * 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} coordinates Coordinates * @param {Object} [options={}] Optional Parameters * @param {Array} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Geometry * @returns {Geometry} a GeoJSON Geometry * @example * var type = 'Point'; * var coordinates = [110, 50]; * * var geometry = turf.geometry(type, coordinates); * * //=geometry */ function helpers_main_es_geometry(type, coordinates, options) { // Optional Parameters options = options || {}; if (!_turf_helpers_main_es_isObject(options)) throw new Error('options is invalid'); var bbox = options.bbox; // Validation if (!type) throw new Error('type is required'); if (!coordinates) throw new Error('coordinates is required'); if (!Array.isArray(coordinates)) throw new Error('coordinates must be an Array'); if (bbox) helpers_main_es_validateBBox(bbox); // Main var geom; switch (type) { case 'Point': geom = _turf_helpers_main_es_point(coordinates).geometry; break; case 'LineString': geom = _turf_helpers_main_es_lineString(coordinates).geometry; break; case 'Polygon': geom = helpers_main_es_polygon(coordinates).geometry; break; case 'MultiPoint': geom = helpers_main_es_multiPoint(coordinates).geometry; break; case 'MultiLineString': geom = helpers_main_es_multiLineString(coordinates).geometry; break; case 'MultiPolygon': geom = helpers_main_es_multiPolygon(coordinates).geometry; break; default: throw new Error(type + ' is invalid'); } if (bbox) geom.bbox = bbox; return geom; } /** * Creates a {@link Point} {@link Feature} from a Position. * * @name point * @param {Array} 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} [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 Point feature * @example * var point = turf.point([-75.343, 39.984]); * * //=point */ function _turf_helpers_main_es_point(coordinates, properties, options) { if (!coordinates) throw new Error('coordinates is required'); if (!Array.isArray(coordinates)) throw new Error('coordinates must be an Array'); if (coordinates.length < 2) throw new Error('coordinates must be at least 2 numbers long'); if (!_turf_helpers_main_es_isNumber(coordinates[0]) || !_turf_helpers_main_es_isNumber(coordinates[1])) throw new Error('coordinates must contain numbers'); return _turf_helpers_main_es_feature({ type: 'Point', coordinates: coordinates }, properties, options); } /** * Creates a {@link Point} {@link FeatureCollection} from an Array of Point coordinates. * * @name points * @param {Array>} coordinates an array of Points * @param {Object} [properties={}] Translate these properties to each Feature * @param {Object} [options={}] Optional Parameters * @param {Array} [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 Feature * @example * var points = turf.points([ * [-75, 39], * [-80, 45], * [-78, 50] * ]); * * //=points */ function helpers_main_es_points(coordinates, properties, options) { if (!coordinates) throw new Error('coordinates is required'); if (!Array.isArray(coordinates)) throw new Error('coordinates must be an Array'); return helpers_main_es_featureCollection(coordinates.map(function (coords) { return _turf_helpers_main_es_point(coords, properties); }), options); } /** * Creates a {@link Polygon} {@link Feature} from an Array of LinearRings. * * @name polygon * @param {Array>>} 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} [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 Feature * @example * var polygon = turf.polygon([[[-5, 52], [-4, 56], [-2, 51], [-7, 54], [-5, 52]]], { name: 'poly1' }); * * //=polygon */ function helpers_main_es_polygon(coordinates, properties, options) { if (!coordinates) throw new Error('coordinates is required'); for (var i = 0; i < coordinates.length; i++) { var ring = coordinates[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 (i === 0 && j === 0 && !_turf_helpers_main_es_isNumber(ring[0][0]) || !_turf_helpers_main_es_isNumber(ring[0][1])) throw new Error('coordinates must contain numbers'); if (ring[ring.length - 1][j] !== ring[0][j]) { throw new Error('First and last Position are not equivalent.'); } } } return _turf_helpers_main_es_feature({ type: 'Polygon', coordinates: coordinates }, properties, options); } /** * Creates a {@link Polygon} {@link FeatureCollection} from an Array of Polygon coordinates. * * @name polygons * @param {Array>>>} 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} [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 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 helpers_main_es_polygons(coordinates, properties, options) { if (!coordinates) throw new Error('coordinates is required'); if (!Array.isArray(coordinates)) throw new Error('coordinates must be an Array'); return helpers_main_es_featureCollection(coordinates.map(function (coords) { return helpers_main_es_polygon(coords, properties); }), options); } /** * Creates a {@link LineString} {@link Feature} from an Array of Positions. * * @name lineString * @param {Array>} 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} [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 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 _turf_helpers_main_es_lineString(coordinates, properties, options) { if (!coordinates) throw new Error('coordinates is required'); if (coordinates.length < 2) throw new Error('coordinates must be an array of two or more positions'); // Check if first point of LineString contains two numbers if (!_turf_helpers_main_es_isNumber(coordinates[0][1]) || !_turf_helpers_main_es_isNumber(coordinates[0][1])) throw new Error('coordinates must contain numbers'); return _turf_helpers_main_es_feature({ type: 'LineString', coordinates: coordinates }, properties, options); } /** * Creates a {@link LineString} {@link FeatureCollection} from an Array of LineString coordinates. * * @name lineStrings * @param {Array>} 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} [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 FeatureCollection * @example * var linestrings = turf.lineStrings([ * [[-24, 63], [-23, 60], [-25, 65], [-20, 69]], * [[-14, 43], [-13, 40], [-15, 45], [-10, 49]] * ]); * * //=linestrings */ function helpers_main_es_lineStrings(coordinates, properties, options) { if (!coordinates) throw new Error('coordinates is required'); if (!Array.isArray(coordinates)) throw new Error('coordinates must be an Array'); return helpers_main_es_featureCollection(coordinates.map(function (coords) { return _turf_helpers_main_es_lineString(coords, properties); }), options); } /** * 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} [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 helpers_main_es_featureCollection(features, options) { // Optional Parameters options = options || {}; if (!_turf_helpers_main_es_isObject(options)) throw new Error('options is invalid'); var bbox = options.bbox; var id = options.id; // Validation if (!features) throw new Error('No features passed'); if (!Array.isArray(features)) throw new Error('features must be an Array'); if (bbox) helpers_main_es_validateBBox(bbox); if (id) helpers_main_es_validateId(id); // Main var fc = {type: 'FeatureCollection'}; if (id) fc.id = id; if (bbox) fc.bbox = bbox; fc.features = features; return fc; } /** * Creates a {@link Feature} based on a * coordinate array. Properties can be added optionally. * * @name multiLineString * @param {Array>>} 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} [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 MultiLineString feature * @throws {Error} if no coordinates are passed * @example * var multiLine = turf.multiLineString([[[0,0],[10,10]]]); * * //=multiLine */ function helpers_main_es_multiLineString(coordinates, properties, options) { if (!coordinates) throw new Error('coordinates is required'); return _turf_helpers_main_es_feature({ type: 'MultiLineString', coordinates: coordinates }, properties, options); } /** * Creates a {@link Feature} based on a * coordinate array. Properties can be added optionally. * * @name multiPoint * @param {Array>} 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} [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 MultiPoint feature * @throws {Error} if no coordinates are passed * @example * var multiPt = turf.multiPoint([[0,0],[10,10]]); * * //=multiPt */ function helpers_main_es_multiPoint(coordinates, properties, options) { if (!coordinates) throw new Error('coordinates is required'); return _turf_helpers_main_es_feature({ type: 'MultiPoint', coordinates: coordinates }, properties, options); } /** * Creates a {@link Feature} based on a * coordinate array. Properties can be added optionally. * * @name multiPolygon * @param {Array>>>} 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} [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 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 helpers_main_es_multiPolygon(coordinates, properties, options) { if (!coordinates) throw new Error('coordinates is required'); return _turf_helpers_main_es_feature({ type: 'MultiPolygon', coordinates: coordinates }, properties, options); } /** * Creates a {@link Feature} based on a * coordinate array. Properties can be added optionally. * * @name geometryCollection * @param {Array} 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} [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 GeometryCollection Feature * @example * var pt = { * "type": "Point", * "coordinates": [100, 0] * }; * var line = { * "type": "LineString", * "coordinates": [ [101, 0], [102, 1] ] * }; * var collection = turf.geometryCollection([pt, line]); * * //=collection */ function helpers_main_es_geometryCollection(geometries, properties, options) { if (!geometries) throw new Error('geometries is required'); if (!Array.isArray(geometries)) throw new Error('geometries must be an Array'); return _turf_helpers_main_es_feature({ type: 'GeometryCollection', geometries: geometries }, properties, options); } /** * 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 helpers_main_es_round(num, precision) { if (num === undefined || num === null || isNaN(num)) throw new Error('num is required'); 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; } /** * 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 helpers_main_es_radiansToLength(radians, units) { if (radians === undefined || radians === null) throw new Error('radians is required'); if (units && typeof units !== 'string') throw new Error('units must be a string'); var factor = helpers_main_es_factors[units || 'kilometers']; if (!factor) throw new Error(units + ' units is invalid'); return radians * factor; } /** * 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 helpers_main_es_lengthToRadians(distance, units) { if (distance === undefined || distance === null) throw new Error('distance is required'); if (units && typeof units !== 'string') throw new Error('units must be a string'); var factor = helpers_main_es_factors[units || 'kilometers']; if (!factor) throw new Error(units + ' units is invalid'); return distance / factor; } /** * 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 helpers_main_es_lengthToDegrees(distance, units) { return helpers_main_es_radiansToDegrees(helpers_main_es_lengthToRadians(distance, units)); } /** * 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 helpers_main_es_bearingToAzimuth(bearing) { if (bearing === null || bearing === undefined) throw new Error('bearing is required'); var angle = bearing % 360; if (angle < 0) angle += 360; return angle; } /** * Converts an angle in radians to degrees * * @name radiansToDegrees * @param {number} radians angle in radians * @returns {number} degrees between 0 and 360 degrees */ function helpers_main_es_radiansToDegrees(radians) { if (radians === null || radians === undefined) throw new Error('radians is required'); var degrees = radians % (2 * Math.PI); return degrees * 180 / Math.PI; } /** * Converts an angle in degrees to radians * * @name degreesToRadians * @param {number} degrees angle between 0 and 360 degrees * @returns {number} angle in radians */ function helpers_main_es_degreesToRadians(degrees) { if (degrees === null || degrees === undefined) throw new Error('degrees is required'); var radians = degrees % 360; return radians * Math.PI / 180; } /** * 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 {string} originalUnit of the length * @param {string} [finalUnit='kilometers'] returned unit * @returns {number} the converted length */ function helpers_main_es_convertLength(length, originalUnit, finalUnit) { if (length === null || length === undefined) throw new Error('length is required'); if (!(length >= 0)) throw new Error('length must be a positive number'); return helpers_main_es_radiansToLength(helpers_main_es_lengthToRadians(length, originalUnit), finalUnit || 'kilometers'); } /** * 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 {string} [originalUnit='meters'] of the distance * @param {string} [finalUnit='kilometers'] returned unit * @returns {number} the converted distance */ function helpers_main_es_convertArea(area, originalUnit, finalUnit) { if (area === null || area === undefined) throw new Error('area is required'); if (!(area >= 0)) throw new Error('area must be a positive number'); var startFactor = helpers_main_es_areaFactors[originalUnit || 'meters']; if (!startFactor) throw new Error('invalid original units'); var finalFactor = helpers_main_es_areaFactors[finalUnit || 'kilometers']; if (!finalFactor) throw new Error('invalid final units'); return (area / startFactor) * finalFactor; } /** * isNumber * * @param {*} num Number to validate * @returns {boolean} true/false * @example * turf.isNumber(123) * //=true * turf.isNumber('foo') * //=false */ function _turf_helpers_main_es_isNumber(num) { return !isNaN(num) && num !== null && !Array.isArray(num); } /** * isObject * * @param {*} input variable to validate * @returns {boolean} true/false * @example * turf.isObject({elevation: 10}) * //=true * turf.isObject('foo') * //=false */ function _turf_helpers_main_es_isObject(input) { return (!!input) && (input.constructor === Object); } /** * Validate BBox * * @private * @param {Array} 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 helpers_main_es_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 (!_turf_helpers_main_es_isNumber(num)) throw new Error('bbox must only contain numbers'); }); } /** * 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 helpers_main_es_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'); } // Deprecated methods function helpers_main_es_radians2degrees() { throw new Error('method has been renamed to `radiansToDegrees`'); } function helpers_main_es_degrees2radians() { throw new Error('method has been renamed to `degreesToRadians`'); } function helpers_main_es_distanceToDegrees() { throw new Error('method has been renamed to `lengthToDegrees`'); } function helpers_main_es_distanceToRadians() { throw new Error('method has been renamed to `lengthToRadians`'); } function helpers_main_es_radiansToDistance() { throw new Error('method has been renamed to `radiansToLength`'); } function helpers_main_es_bearingToAngle() { throw new Error('method has been renamed to `bearingToAzimuth`'); } function helpers_main_es_convertDistance() { throw new Error('method has been renamed to `convertLength`'); } ;// CONCATENATED MODULE: ./node_modules/@turf/transform-scale/node_modules/@turf/meta/main.es.js /** * Callback for coordEach * * @callback coordEachCallback * @param {Array} 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 meta_main_es_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++) { if (geomType === 'MultiPolygon') 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 (meta_main_es_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} 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 meta_main_es_coordReduce(geojson, callback, initialValue, excludeWrapCoord) { var previousValue = initialValue; meta_main_es_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 meta_main_es_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|Feature} geojson any GeoJSON object * @param {Function} callback a method that takes (previousValue, currentProperties, featureIndex) * @param {*} [initialValue] Value to use as the first argument to the first call of the callback. * @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.propReduce(features, function (previousValue, currentProperties, featureIndex) { * //=previousValue * //=currentProperties * //=featureIndex * return currentProperties * }); */ function meta_main_es_propReduce(geojson, callback, initialValue) { var previousValue = initialValue; meta_main_es_propEach(geojson, function (currentProperties, featureIndex) { if (featureIndex === 0 && initialValue === undefined) previousValue = currentProperties; else previousValue = callback(previousValue, currentProperties, featureIndex); }); return previousValue; } /** * Callback for featureEach * * @callback featureEachCallback * @param {Feature} currentFeature The current Feature being processed. * @param {number} featureIndex The current index of the Feature being processed. */ /** * Iterate over features in any GeoJSON object, similar to * Array.forEach. * * @name featureEach * @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON object * @param {Function} callback a method that takes (currentFeature, featureIndex) * @returns {void} * @example * var features = turf.featureCollection([ * turf.point([26, 37], {foo: 'bar'}), * turf.point([36, 53], {hello: 'world'}) * ]); * * turf.featureEach(features, function (currentFeature, featureIndex) { * //=currentFeature * //=featureIndex * }); */ function meta_main_es_featureEach(geojson, callback) { if (geojson.type === 'Feature') { callback(geojson, 0); } else if (geojson.type === 'FeatureCollection') { for (var i = 0; i < geojson.features.length; i++) { if (callback(geojson.features[i], i) === false) break; } } } /** * Callback for featureReduce * * 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 featureReduceCallback * @param {*} previousValue The accumulated value previously returned in the last invocation * of the callback, or initialValue, if supplied. * @param {Feature} currentFeature The current Feature being processed. * @param {number} featureIndex The current index of the Feature being processed. */ /** * Reduce features in any GeoJSON object, similar to Array.reduce(). * * @name featureReduce * @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON object * @param {Function} callback a method that takes (previousValue, currentFeature, featureIndex) * @param {*} [initialValue] Value to use as the first argument to the first call of the callback. * @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.featureReduce(features, function (previousValue, currentFeature, featureIndex) { * //=previousValue * //=currentFeature * //=featureIndex * return currentFeature * }); */ function meta_main_es_featureReduce(geojson, callback, initialValue) { var previousValue = initialValue; meta_main_es_featureEach(geojson, function (currentFeature, featureIndex) { if (featureIndex === 0 && initialValue === undefined) previousValue = currentFeature; else previousValue = callback(previousValue, currentFeature, featureIndex); }); return previousValue; } /** * Get all coordinates from any GeoJSON object. * * @name coordAll * @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON object * @returns {Array>} coordinate position array * @example * var features = turf.featureCollection([ * turf.point([26, 37], {foo: 'bar'}), * turf.point([36, 53], {hello: 'world'}) * ]); * * var coords = turf.coordAll(features); * //= [[26, 37], [36, 53]] */ function meta_main_es_coordAll(geojson) { var coords = []; meta_main_es_coordEach(geojson, function (coord) { coords.push(coord); }); return coords; } /** * Callback for geomEach * * @callback geomEachCallback * @param {Geometry} currentGeometry The current Geometry being processed. * @param {number} featureIndex The current index of the Feature being processed. * @param {Object} featureProperties The current Feature Properties being processed. * @param {Array} featureBBox The current Feature BBox being processed. * @param {number|string} featureId The current Feature Id being processed. */ /** * Iterate over each geometry in any GeoJSON object, similar to Array.forEach() * * @name geomEach * @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON object * @param {Function} callback a method that takes (currentGeometry, featureIndex, featureProperties, featureBBox, featureId) * @returns {void} * @example * var features = turf.featureCollection([ * turf.point([26, 37], {foo: 'bar'}), * turf.point([36, 53], {hello: 'world'}) * ]); * * turf.geomEach(features, function (currentGeometry, featureIndex, featureProperties, featureBBox, featureId) { * //=currentGeometry * //=featureIndex * //=featureProperties * //=featureBBox * //=featureId * }); */ function meta_main_es_geomEach(geojson, callback) { var i, j, g, geometry, stopG, geometryMaybeCollection, isGeometryCollection, featureProperties, featureBBox, featureId, featureIndex = 0, isFeatureCollection = geojson.type === 'FeatureCollection', isFeature = geojson.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 (i = 0; i < stop; i++) { geometryMaybeCollection = (isFeatureCollection ? geojson.features[i].geometry : (isFeature ? geojson.geometry : geojson)); featureProperties = (isFeatureCollection ? geojson.features[i].properties : (isFeature ? geojson.properties : {})); featureBBox = (isFeatureCollection ? geojson.features[i].bbox : (isFeature ? geojson.bbox : undefined)); featureId = (isFeatureCollection ? geojson.features[i].id : (isFeature ? geojson.id : undefined)); isGeometryCollection = (geometryMaybeCollection) ? geometryMaybeCollection.type === 'GeometryCollection' : false; stopG = isGeometryCollection ? geometryMaybeCollection.geometries.length : 1; for (g = 0; g < stopG; g++) { geometry = isGeometryCollection ? geometryMaybeCollection.geometries[g] : geometryMaybeCollection; // Handle null Geometry if (geometry === null) { if (callback(null, featureIndex, featureProperties, featureBBox, featureId) === false) return false; continue; } switch (geometry.type) { case 'Point': case 'LineString': case 'MultiPoint': case 'Polygon': case 'MultiLineString': case 'MultiPolygon': { if (callback(geometry, featureIndex, featureProperties, featureBBox, featureId) === false) return false; break; } case 'GeometryCollection': { for (j = 0; j < geometry.geometries.length; j++) { if (callback(geometry.geometries[j], featureIndex, featureProperties, featureBBox, featureId) === false) return false; } break; } default: throw new Error('Unknown Geometry Type'); } } // Only increase `featureIndex` per each feature featureIndex++; } } /** * Callback for geomReduce * * 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 geomReduceCallback * @param {*} previousValue The accumulated value previously returned in the last invocation * of the callback, or initialValue, if supplied. * @param {Geometry} currentGeometry The current Geometry being processed. * @param {number} featureIndex The current index of the Feature being processed. * @param {Object} featureProperties The current Feature Properties being processed. * @param {Array} featureBBox The current Feature BBox being processed. * @param {number|string} featureId The current Feature Id being processed. */ /** * Reduce geometry in any GeoJSON object, similar to Array.reduce(). * * @name geomReduce * @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON object * @param {Function} callback a method that takes (previousValue, currentGeometry, featureIndex, featureProperties, featureBBox, featureId) * @param {*} [initialValue] Value to use as the first argument to the first call of the callback. * @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.geomReduce(features, function (previousValue, currentGeometry, featureIndex, featureProperties, featureBBox, featureId) { * //=previousValue * //=currentGeometry * //=featureIndex * //=featureProperties * //=featureBBox * //=featureId * return currentGeometry * }); */ function meta_main_es_geomReduce(geojson, callback, initialValue) { var previousValue = initialValue; meta_main_es_geomEach(geojson, function (currentGeometry, featureIndex, featureProperties, featureBBox, featureId) { if (featureIndex === 0 && initialValue === undefined) previousValue = currentGeometry; else previousValue = callback(previousValue, currentGeometry, featureIndex, featureProperties, featureBBox, featureId); }); return previousValue; } /** * Callback for flattenEach * * @callback flattenEachCallback * @param {Feature} currentFeature The current flattened feature 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. */ /** * Iterate over flattened features in any GeoJSON object, similar to * Array.forEach. * * @name flattenEach * @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON object * @param {Function} callback a method that takes (currentFeature, featureIndex, multiFeatureIndex) * @example * var features = turf.featureCollection([ * turf.point([26, 37], {foo: 'bar'}), * turf.multiPoint([[40, 30], [36, 53]], {hello: 'world'}) * ]); * * turf.flattenEach(features, function (currentFeature, featureIndex, multiFeatureIndex) { * //=currentFeature * //=featureIndex * //=multiFeatureIndex * }); */ function meta_main_es_flattenEach(geojson, callback) { meta_main_es_geomEach(geojson, function (geometry, featureIndex, properties, bbox, id) { // Callback for single geometry var type = (geometry === null) ? null : geometry.type; switch (type) { case null: case 'Point': case 'LineString': case 'Polygon': if (callback(feature(geometry, properties, {bbox: bbox, id: id}), featureIndex, 0) === false) return false; return; } var geomType; // Callback for multi-geometry switch (type) { case 'MultiPoint': geomType = 'Point'; break; case 'MultiLineString': geomType = 'LineString'; break; case 'MultiPolygon': geomType = 'Polygon'; break; } for (var multiFeatureIndex = 0; multiFeatureIndex < geometry.coordinates.length; multiFeatureIndex++) { var coordinate = geometry.coordinates[multiFeatureIndex]; var geom = { type: geomType, coordinates: coordinate }; if (callback(feature(geom, properties), featureIndex, multiFeatureIndex) === false) return false; } }); } /** * Callback for flattenReduce * * 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 flattenReduceCallback * @param {*} previousValue The accumulated value previously returned in the last invocation * of the callback, or initialValue, if supplied. * @param {Feature} currentFeature The current Feature 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. */ /** * Reduce flattened features in any GeoJSON object, similar to Array.reduce(). * * @name flattenReduce * @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON object * @param {Function} callback a method that takes (previousValue, currentFeature, featureIndex, multiFeatureIndex) * @param {*} [initialValue] Value to use as the first argument to the first call of the callback. * @returns {*} The value that results from the reduction. * @example * var features = turf.featureCollection([ * turf.point([26, 37], {foo: 'bar'}), * turf.multiPoint([[40, 30], [36, 53]], {hello: 'world'}) * ]); * * turf.flattenReduce(features, function (previousValue, currentFeature, featureIndex, multiFeatureIndex) { * //=previousValue * //=currentFeature * //=featureIndex * //=multiFeatureIndex * return currentFeature * }); */ function meta_main_es_flattenReduce(geojson, callback, initialValue) { var previousValue = initialValue; meta_main_es_flattenEach(geojson, function (currentFeature, featureIndex, multiFeatureIndex) { if (featureIndex === 0 && multiFeatureIndex === 0 && initialValue === undefined) previousValue = currentFeature; else previousValue = callback(previousValue, currentFeature, featureIndex, multiFeatureIndex); }); return previousValue; } /** * Callback for segmentEach * * @callback segmentEachCallback * @param {Feature} currentSegment The current Segment 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. * @param {number} segmentIndex The current index of the Segment being processed. * @returns {void} */ /** * Iterate over 2-vertex line segment in any GeoJSON object, similar to Array.forEach() * (Multi)Point geometries do not contain segments therefore they are ignored during this operation. * * @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON * @param {Function} callback a method that takes (currentSegment, featureIndex, multiFeatureIndex, geometryIndex, segmentIndex) * @returns {void} * @example * var polygon = turf.polygon([[[-50, 5], [-40, -10], [-50, -10], [-40, 5], [-50, 5]]]); * * // Iterate over GeoJSON by 2-vertex segments * turf.segmentEach(polygon, function (currentSegment, featureIndex, multiFeatureIndex, geometryIndex, segmentIndex) { * //=currentSegment * //=featureIndex * //=multiFeatureIndex * //=geometryIndex * //=segmentIndex * }); * * // Calculate the total number of segments * var total = 0; * turf.segmentEach(polygon, function () { * total++; * }); */ function meta_main_es_segmentEach(geojson, callback) { meta_main_es_flattenEach(geojson, function (feature$$1, featureIndex, multiFeatureIndex) { var segmentIndex = 0; // Exclude null Geometries if (!feature$$1.geometry) return; // (Multi)Point geometries do not contain segments therefore they are ignored during this operation. var type = feature$$1.geometry.type; if (type === 'Point' || type === 'MultiPoint') return; // Generate 2-vertex line segments var previousCoords; if (meta_main_es_coordEach(feature$$1, function (currentCoord, coordIndex, featureIndexCoord, mutliPartIndexCoord, geometryIndex) { // Simulating a meta.coordReduce() since `reduce` operations cannot be stopped by returning `false` if (previousCoords === undefined) { previousCoords = currentCoord; return; } var currentSegment = lineString([previousCoords, currentCoord], feature$$1.properties); if (callback(currentSegment, featureIndex, multiFeatureIndex, geometryIndex, segmentIndex) === false) return false; segmentIndex++; previousCoords = currentCoord; }) === false) return false; }); } /** * Callback for segmentReduce * * 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 segmentReduceCallback * @param {*} previousValue The accumulated value previously returned in the last invocation * of the callback, or initialValue, if supplied. * @param {Feature} currentSegment The current Segment 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. * @param {number} segmentIndex The current index of the Segment being processed. */ /** * Reduce 2-vertex line segment in any GeoJSON object, similar to Array.reduce() * (Multi)Point geometries do not contain segments therefore they are ignored during this operation. * * @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON * @param {Function} callback a method that takes (previousValue, currentSegment, currentIndex) * @param {*} [initialValue] Value to use as the first argument to the first call of the callback. * @returns {void} * @example * var polygon = turf.polygon([[[-50, 5], [-40, -10], [-50, -10], [-40, 5], [-50, 5]]]); * * // Iterate over GeoJSON by 2-vertex segments * turf.segmentReduce(polygon, function (previousSegment, currentSegment, featureIndex, multiFeatureIndex, geometryIndex, segmentIndex) { * //= previousSegment * //= currentSegment * //= featureIndex * //= multiFeatureIndex * //= geometryIndex * //= segmentInex * return currentSegment * }); * * // Calculate the total number of segments * var initialValue = 0 * var total = turf.segmentReduce(polygon, function (previousValue) { * previousValue++; * return previousValue; * }, initialValue); */ function meta_main_es_segmentReduce(geojson, callback, initialValue) { var previousValue = initialValue; var started = false; meta_main_es_segmentEach(geojson, function (currentSegment, featureIndex, multiFeatureIndex, geometryIndex, segmentIndex) { if (started === false && initialValue === undefined) previousValue = currentSegment; else previousValue = callback(previousValue, currentSegment, featureIndex, multiFeatureIndex, geometryIndex, segmentIndex); started = true; }); return previousValue; } /** * Callback for lineEach * * @callback lineEachCallback * @param {Feature} currentLine The current LineString|LinearRing 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 line or ring coordinates in LineString, Polygon, MultiLineString, MultiPolygon Features or Geometries, * similar to Array.forEach. * * @name lineEach * @param {Geometry|Feature} geojson object * @param {Function} callback a method that takes (currentLine, featureIndex, multiFeatureIndex, geometryIndex) * @example * var multiLine = turf.multiLineString([ * [[26, 37], [35, 45]], * [[36, 53], [38, 50], [41, 55]] * ]); * * turf.lineEach(multiLine, function (currentLine, featureIndex, multiFeatureIndex, geometryIndex) { * //=currentLine * //=featureIndex * //=multiFeatureIndex * //=geometryIndex * }); */ function meta_main_es_lineEach(geojson, callback) { // validation if (!geojson) throw new Error('geojson is required'); meta_main_es_flattenEach(geojson, function (feature$$1, featureIndex, multiFeatureIndex) { if (feature$$1.geometry === null) return; var type = feature$$1.geometry.type; var coords = feature$$1.geometry.coordinates; switch (type) { case 'LineString': if (callback(feature$$1, featureIndex, multiFeatureIndex, 0, 0) === false) return false; break; case 'Polygon': for (var geometryIndex = 0; geometryIndex < coords.length; geometryIndex++) { if (callback(lineString(coords[geometryIndex], feature$$1.properties), featureIndex, multiFeatureIndex, geometryIndex) === false) return false; } break; } }); } /** * Callback for lineReduce * * 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 lineReduceCallback * @param {*} previousValue The accumulated value previously returned in the last invocation * of the callback, or initialValue, if supplied. * @param {Feature} currentLine The current LineString|LinearRing 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 */ /** * Reduce features in any GeoJSON object, similar to Array.reduce(). * * @name lineReduce * @param {Geometry|Feature} geojson object * @param {Function} callback a method that takes (previousValue, currentLine, featureIndex, multiFeatureIndex, geometryIndex) * @param {*} [initialValue] Value to use as the first argument to the first call of the callback. * @returns {*} The value that results from the reduction. * @example * var multiPoly = turf.multiPolygon([ * turf.polygon([[[12,48],[2,41],[24,38],[12,48]], [[9,44],[13,41],[13,45],[9,44]]]), * turf.polygon([[[5, 5], [0, 0], [2, 2], [4, 4], [5, 5]]]) * ]); * * turf.lineReduce(multiPoly, function (previousValue, currentLine, featureIndex, multiFeatureIndex, geometryIndex) { * //=previousValue * //=currentLine * //=featureIndex * //=multiFeatureIndex * //=geometryIndex * return currentLine * }); */ function meta_main_es_lineReduce(geojson, callback, initialValue) { var previousValue = initialValue; meta_main_es_lineEach(geojson, function (currentLine, featureIndex, multiFeatureIndex, geometryIndex) { if (featureIndex === 0 && initialValue === undefined) previousValue = currentLine; else previousValue = callback(previousValue, currentLine, featureIndex, multiFeatureIndex, geometryIndex); }); return previousValue; } /** * Finds a particular 2-vertex LineString Segment from a GeoJSON using `@turf/meta` indexes. * * Negative indexes are permitted. * Point & MultiPoint will always return null. * * @param {FeatureCollection|Feature|Geometry} geojson Any GeoJSON Feature or Geometry * @param {Object} [options={}] Optional parameters * @param {number} [options.featureIndex=0] Feature Index * @param {number} [options.multiFeatureIndex=0] Multi-Feature Index * @param {number} [options.geometryIndex=0] Geometry Index * @param {number} [options.segmentIndex=0] Segment Index * @param {Object} [options.properties={}] Translate Properties to output LineString * @param {BBox} [options.bbox={}] Translate BBox to output LineString * @param {number|string} [options.id={}] Translate Id to output LineString * @returns {Feature} 2-vertex GeoJSON Feature LineString * @example * var multiLine = turf.multiLineString([ * [[10, 10], [50, 30], [30, 40]], * [[-10, -10], [-50, -30], [-30, -40]] * ]); * * // First Segment (defaults are 0) * turf.findSegment(multiLine); * // => Feature> * * // First Segment of 2nd Multi Feature * turf.findSegment(multiLine, {multiFeatureIndex: 1}); * // => Feature> * * // Last Segment of Last Multi Feature * turf.findSegment(multiLine, {multiFeatureIndex: -1, segmentIndex: -1}); * // => Feature> */ function meta_main_es_findSegment(geojson, options) { // Optional Parameters options = options || {}; if (!isObject(options)) throw new Error('options is invalid'); var featureIndex = options.featureIndex || 0; var multiFeatureIndex = options.multiFeatureIndex || 0; var geometryIndex = options.geometryIndex || 0; var segmentIndex = options.segmentIndex || 0; // Find FeatureIndex var properties = options.properties; var geometry; switch (geojson.type) { case 'FeatureCollection': if (featureIndex < 0) featureIndex = geojson.features.length + featureIndex; properties = properties || geojson.features[featureIndex].properties; geometry = geojson.features[featureIndex].geometry; break; case 'Feature': properties = properties || geojson.properties; geometry = geojson.geometry; break; case 'Point': case 'MultiPoint': return null; case 'LineString': case 'Polygon': case 'MultiLineString': case 'MultiPolygon': geometry = geojson; break; default: throw new Error('geojson is invalid'); } // Find SegmentIndex if (geometry === null) return null; var coords = geometry.coordinates; switch (geometry.type) { case 'Point': case 'MultiPoint': return null; case 'LineString': if (segmentIndex < 0) segmentIndex = coords.length + segmentIndex - 1; return lineString([coords[segmentIndex], coords[segmentIndex + 1]], properties, options); case 'Polygon': if (geometryIndex < 0) geometryIndex = coords.length + geometryIndex; if (segmentIndex < 0) segmentIndex = coords[geometryIndex].length + segmentIndex - 1; return lineString([coords[geometryIndex][segmentIndex], coords[geometryIndex][segmentIndex + 1]], properties, options); case 'MultiLineString': if (multiFeatureIndex < 0) multiFeatureIndex = coords.length + multiFeatureIndex; if (segmentIndex < 0) segmentIndex = coords[multiFeatureIndex].length + segmentIndex - 1; return lineString([coords[multiFeatureIndex][segmentIndex], coords[multiFeatureIndex][segmentIndex + 1]], properties, options); case 'MultiPolygon': if (multiFeatureIndex < 0) multiFeatureIndex = coords.length + multiFeatureIndex; if (geometryIndex < 0) geometryIndex = coords[multiFeatureIndex].length + geometryIndex; if (segmentIndex < 0) segmentIndex = coords[multiFeatureIndex][geometryIndex].length - segmentIndex - 1; return lineString([coords[multiFeatureIndex][geometryIndex][segmentIndex], coords[multiFeatureIndex][geometryIndex][segmentIndex + 1]], properties, options); } throw new Error('geojson is invalid'); } /** * Finds a particular Point from a GeoJSON using `@turf/meta` indexes. * * Negative indexes are permitted. * * @param {FeatureCollection|Feature|Geometry} geojson Any GeoJSON Feature or Geometry * @param {Object} [options={}] Optional parameters * @param {number} [options.featureIndex=0] Feature Index * @param {number} [options.multiFeatureIndex=0] Multi-Feature Index * @param {number} [options.geometryIndex=0] Geometry Index * @param {number} [options.coordIndex=0] Coord Index * @param {Object} [options.properties={}] Translate Properties to output Point * @param {BBox} [options.bbox={}] Translate BBox to output Point * @param {number|string} [options.id={}] Translate Id to output Point * @returns {Feature} 2-vertex GeoJSON Feature Point * @example * var multiLine = turf.multiLineString([ * [[10, 10], [50, 30], [30, 40]], * [[-10, -10], [-50, -30], [-30, -40]] * ]); * * // First Segment (defaults are 0) * turf.findPoint(multiLine); * // => Feature> * * // First Segment of the 2nd Multi-Feature * turf.findPoint(multiLine, {multiFeatureIndex: 1}); * // => Feature> * * // Last Segment of last Multi-Feature * turf.findPoint(multiLine, {multiFeatureIndex: -1, coordIndex: -1}); * // => Feature> */ function meta_main_es_findPoint(geojson, options) { // Optional Parameters options = options || {}; if (!isObject(options)) throw new Error('options is invalid'); var featureIndex = options.featureIndex || 0; var multiFeatureIndex = options.multiFeatureIndex || 0; var geometryIndex = options.geometryIndex || 0; var coordIndex = options.coordIndex || 0; // Find FeatureIndex var properties = options.properties; var geometry; switch (geojson.type) { case 'FeatureCollection': if (featureIndex < 0) featureIndex = geojson.features.length + featureIndex; properties = properties || geojson.features[featureIndex].properties; geometry = geojson.features[featureIndex].geometry; break; case 'Feature': properties = properties || geojson.properties; geometry = geojson.geometry; break; case 'Point': case 'MultiPoint': return null; case 'LineString': case 'Polygon': case 'MultiLineString': case 'MultiPolygon': geometry = geojson; break; default: throw new Error('geojson is invalid'); } // Find Coord Index if (geometry === null) return null; var coords = geometry.coordinates; switch (geometry.type) { case 'Point': return point(coords, properties, options); case 'MultiPoint': if (multiFeatureIndex < 0) multiFeatureIndex = coords.length + multiFeatureIndex; return point(coords[multiFeatureIndex], properties, options); case 'LineString': if (coordIndex < 0) coordIndex = coords.length + coordIndex; return point(coords[coordIndex], properties, options); case 'Polygon': if (geometryIndex < 0) geometryIndex = coords.length + geometryIndex; if (coordIndex < 0) coordIndex = coords[geometryIndex].length + coordIndex; return point(coords[geometryIndex][coordIndex], properties, options); case 'MultiLineString': if (multiFeatureIndex < 0) multiFeatureIndex = coords.length + multiFeatureIndex; if (coordIndex < 0) coordIndex = coords[multiFeatureIndex].length + coordIndex; return point(coords[multiFeatureIndex][coordIndex], properties, options); case 'MultiPolygon': if (multiFeatureIndex < 0) multiFeatureIndex = coords.length + multiFeatureIndex; if (geometryIndex < 0) geometryIndex = coords[multiFeatureIndex].length + geometryIndex; if (coordIndex < 0) coordIndex = coords[multiFeatureIndex][geometryIndex].length - coordIndex; return point(coords[multiFeatureIndex][geometryIndex][coordIndex], properties, options); } throw new Error('geojson is invalid'); } ;// CONCATENATED MODULE: ./node_modules/@turf/transform-scale/node_modules/@turf/bbox/main.es.js /** * 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 main_es_bbox(geojson) { var BBox = [Infinity, Infinity, -Infinity, -Infinity]; meta_main_es_coordEach(geojson, function (coord) { if (BBox[0] > coord[0]) BBox[0] = coord[0]; if (BBox[1] > coord[1]) BBox[1] = coord[1]; if (BBox[2] < coord[0]) BBox[2] = coord[0]; if (BBox[3] < coord[1]) BBox[3] = coord[1]; }); return BBox; } /* harmony default export */ var _turf_bbox_main_es = (main_es_bbox); ;// CONCATENATED MODULE: ./node_modules/@turf/invariant/node_modules/@turf/helpers/main.es.js /** * Earth Radius used with the Harvesine formula and approximates using a spherical (non-ellipsoid) Earth. */ var _turf_helpers_main_es_earthRadius = 6371008.8; /** * Unit of measurement factors using a spherical (non-ellipsoid) earth radius. */ var _turf_helpers_main_es_factors = { meters: _turf_helpers_main_es_earthRadius, metres: _turf_helpers_main_es_earthRadius, millimeters: _turf_helpers_main_es_earthRadius * 1000, millimetres: _turf_helpers_main_es_earthRadius * 1000, centimeters: _turf_helpers_main_es_earthRadius * 100, centimetres: _turf_helpers_main_es_earthRadius * 100, kilometers: _turf_helpers_main_es_earthRadius / 1000, kilometres: _turf_helpers_main_es_earthRadius / 1000, miles: _turf_helpers_main_es_earthRadius / 1609.344, nauticalmiles: _turf_helpers_main_es_earthRadius / 1852, inches: _turf_helpers_main_es_earthRadius * 39.370, yards: _turf_helpers_main_es_earthRadius / 1.0936, feet: _turf_helpers_main_es_earthRadius * 3.28084, radians: 1, degrees: _turf_helpers_main_es_earthRadius / 111325, }; /** * Units of measurement factors based on 1 meter. */ var _turf_helpers_main_es_unitsFactors = { meters: 1, metres: 1, millimeters: 1000, millimetres: 1000, centimeters: 100, centimetres: 100, kilometers: 1 / 1000, kilometres: 1 / 1000, miles: 1 / 1609.344, nauticalmiles: 1 / 1852, inches: 39.370, yards: 1 / 1.0936, feet: 3.28084, radians: 1 / _turf_helpers_main_es_earthRadius, degrees: 1 / 111325, }; /** * Area of measurement factors based on 1 square meter. */ var _turf_helpers_main_es_areaFactors = { meters: 1, metres: 1, millimeters: 1000000, millimetres: 1000000, centimeters: 10000, centimetres: 10000, kilometers: 0.000001, kilometres: 0.000001, acres: 0.000247105, miles: 3.86e-7, yards: 1.195990046, feet: 10.763910417, inches: 1550.003100006 }; /** * 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} [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 node_modules_turf_helpers_main_es_feature(geometry, properties, options) { // Optional Parameters options = options || {}; if (!node_modules_turf_helpers_main_es_isObject(options)) throw new Error('options is invalid'); var bbox = options.bbox; var id = options.id; // Validation if (geometry === undefined) throw new Error('geometry is required'); if (properties && properties.constructor !== Object) throw new Error('properties must be an Object'); if (bbox) _turf_helpers_main_es_validateBBox(bbox); if (id) _turf_helpers_main_es_validateId(id); // Main var feat = {type: 'Feature'}; if (id) feat.id = id; if (bbox) feat.bbox = bbox; feat.properties = properties || {}; feat.geometry = geometry; return feat; } /** * 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} coordinates Coordinates * @param {Object} [options={}] Optional Parameters * @param {Array} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Geometry * @returns {Geometry} a GeoJSON Geometry * @example * var type = 'Point'; * var coordinates = [110, 50]; * * var geometry = turf.geometry(type, coordinates); * * //=geometry */ function _turf_helpers_main_es_geometry(type, coordinates, options) { // Optional Parameters options = options || {}; if (!node_modules_turf_helpers_main_es_isObject(options)) throw new Error('options is invalid'); var bbox = options.bbox; // Validation if (!type) throw new Error('type is required'); if (!coordinates) throw new Error('coordinates is required'); if (!Array.isArray(coordinates)) throw new Error('coordinates must be an Array'); if (bbox) _turf_helpers_main_es_validateBBox(bbox); // Main var geom; switch (type) { case 'Point': geom = node_modules_turf_helpers_main_es_point(coordinates).geometry; break; case 'LineString': geom = node_modules_turf_helpers_main_es_lineString(coordinates).geometry; break; case 'Polygon': geom = _turf_helpers_main_es_polygon(coordinates).geometry; break; case 'MultiPoint': geom = _turf_helpers_main_es_multiPoint(coordinates).geometry; break; case 'MultiLineString': geom = _turf_helpers_main_es_multiLineString(coordinates).geometry; break; case 'MultiPolygon': geom = _turf_helpers_main_es_multiPolygon(coordinates).geometry; break; default: throw new Error(type + ' is invalid'); } if (bbox) geom.bbox = bbox; return geom; } /** * Creates a {@link Point} {@link Feature} from a Position. * * @name point * @param {Array} 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} [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 Point feature * @example * var point = turf.point([-75.343, 39.984]); * * //=point */ function node_modules_turf_helpers_main_es_point(coordinates, properties, options) { if (!coordinates) throw new Error('coordinates is required'); if (!Array.isArray(coordinates)) throw new Error('coordinates must be an Array'); if (coordinates.length < 2) throw new Error('coordinates must be at least 2 numbers long'); if (!node_modules_turf_helpers_main_es_isNumber(coordinates[0]) || !node_modules_turf_helpers_main_es_isNumber(coordinates[1])) throw new Error('coordinates must contain numbers'); return node_modules_turf_helpers_main_es_feature({ type: 'Point', coordinates: coordinates }, properties, options); } /** * Creates a {@link Point} {@link FeatureCollection} from an Array of Point coordinates. * * @name points * @param {Array>} coordinates an array of Points * @param {Object} [properties={}] Translate these properties to each Feature * @param {Object} [options={}] Optional Parameters * @param {Array} [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 Feature * @example * var points = turf.points([ * [-75, 39], * [-80, 45], * [-78, 50] * ]); * * //=points */ function _turf_helpers_main_es_points(coordinates, properties, options) { if (!coordinates) throw new Error('coordinates is required'); if (!Array.isArray(coordinates)) throw new Error('coordinates must be an Array'); return _turf_helpers_main_es_featureCollection(coordinates.map(function (coords) { return node_modules_turf_helpers_main_es_point(coords, properties); }), options); } /** * Creates a {@link Polygon} {@link Feature} from an Array of LinearRings. * * @name polygon * @param {Array>>} 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} [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 Feature * @example * var polygon = turf.polygon([[[-5, 52], [-4, 56], [-2, 51], [-7, 54], [-5, 52]]], { name: 'poly1' }); * * //=polygon */ function _turf_helpers_main_es_polygon(coordinates, properties, options) { if (!coordinates) throw new Error('coordinates is required'); for (var i = 0; i < coordinates.length; i++) { var ring = coordinates[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 (i === 0 && j === 0 && !node_modules_turf_helpers_main_es_isNumber(ring[0][0]) || !node_modules_turf_helpers_main_es_isNumber(ring[0][1])) throw new Error('coordinates must contain numbers'); if (ring[ring.length - 1][j] !== ring[0][j]) { throw new Error('First and last Position are not equivalent.'); } } } return node_modules_turf_helpers_main_es_feature({ type: 'Polygon', coordinates: coordinates }, properties, options); } /** * Creates a {@link Polygon} {@link FeatureCollection} from an Array of Polygon coordinates. * * @name polygons * @param {Array>>>} 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} [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 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 _turf_helpers_main_es_polygons(coordinates, properties, options) { if (!coordinates) throw new Error('coordinates is required'); if (!Array.isArray(coordinates)) throw new Error('coordinates must be an Array'); return _turf_helpers_main_es_featureCollection(coordinates.map(function (coords) { return _turf_helpers_main_es_polygon(coords, properties); }), options); } /** * Creates a {@link LineString} {@link Feature} from an Array of Positions. * * @name lineString * @param {Array>} 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} [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 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 node_modules_turf_helpers_main_es_lineString(coordinates, properties, options) { if (!coordinates) throw new Error('coordinates is required'); if (coordinates.length < 2) throw new Error('coordinates must be an array of two or more positions'); // Check if first point of LineString contains two numbers if (!node_modules_turf_helpers_main_es_isNumber(coordinates[0][1]) || !node_modules_turf_helpers_main_es_isNumber(coordinates[0][1])) throw new Error('coordinates must contain numbers'); return node_modules_turf_helpers_main_es_feature({ type: 'LineString', coordinates: coordinates }, properties, options); } /** * Creates a {@link LineString} {@link FeatureCollection} from an Array of LineString coordinates. * * @name lineStrings * @param {Array>} 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} [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 FeatureCollection * @example * var linestrings = turf.lineStrings([ * [[-24, 63], [-23, 60], [-25, 65], [-20, 69]], * [[-14, 43], [-13, 40], [-15, 45], [-10, 49]] * ]); * * //=linestrings */ function _turf_helpers_main_es_lineStrings(coordinates, properties, options) { if (!coordinates) throw new Error('coordinates is required'); if (!Array.isArray(coordinates)) throw new Error('coordinates must be an Array'); return _turf_helpers_main_es_featureCollection(coordinates.map(function (coords) { return node_modules_turf_helpers_main_es_lineString(coords, properties); }), options); } /** * 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} [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 _turf_helpers_main_es_featureCollection(features, options) { // Optional Parameters options = options || {}; if (!node_modules_turf_helpers_main_es_isObject(options)) throw new Error('options is invalid'); var bbox = options.bbox; var id = options.id; // Validation if (!features) throw new Error('No features passed'); if (!Array.isArray(features)) throw new Error('features must be an Array'); if (bbox) _turf_helpers_main_es_validateBBox(bbox); if (id) _turf_helpers_main_es_validateId(id); // Main var fc = {type: 'FeatureCollection'}; if (id) fc.id = id; if (bbox) fc.bbox = bbox; fc.features = features; return fc; } /** * Creates a {@link Feature} based on a * coordinate array. Properties can be added optionally. * * @name multiLineString * @param {Array>>} 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} [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 MultiLineString feature * @throws {Error} if no coordinates are passed * @example * var multiLine = turf.multiLineString([[[0,0],[10,10]]]); * * //=multiLine */ function _turf_helpers_main_es_multiLineString(coordinates, properties, options) { if (!coordinates) throw new Error('coordinates is required'); return node_modules_turf_helpers_main_es_feature({ type: 'MultiLineString', coordinates: coordinates }, properties, options); } /** * Creates a {@link Feature} based on a * coordinate array. Properties can be added optionally. * * @name multiPoint * @param {Array>} 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} [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 MultiPoint feature * @throws {Error} if no coordinates are passed * @example * var multiPt = turf.multiPoint([[0,0],[10,10]]); * * //=multiPt */ function _turf_helpers_main_es_multiPoint(coordinates, properties, options) { if (!coordinates) throw new Error('coordinates is required'); return node_modules_turf_helpers_main_es_feature({ type: 'MultiPoint', coordinates: coordinates }, properties, options); } /** * Creates a {@link Feature} based on a * coordinate array. Properties can be added optionally. * * @name multiPolygon * @param {Array>>>} 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} [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 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 _turf_helpers_main_es_multiPolygon(coordinates, properties, options) { if (!coordinates) throw new Error('coordinates is required'); return node_modules_turf_helpers_main_es_feature({ type: 'MultiPolygon', coordinates: coordinates }, properties, options); } /** * Creates a {@link Feature} based on a * coordinate array. Properties can be added optionally. * * @name geometryCollection * @param {Array} 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} [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 GeometryCollection Feature * @example * var pt = { * "type": "Point", * "coordinates": [100, 0] * }; * var line = { * "type": "LineString", * "coordinates": [ [101, 0], [102, 1] ] * }; * var collection = turf.geometryCollection([pt, line]); * * //=collection */ function _turf_helpers_main_es_geometryCollection(geometries, properties, options) { if (!geometries) throw new Error('geometries is required'); if (!Array.isArray(geometries)) throw new Error('geometries must be an Array'); return node_modules_turf_helpers_main_es_feature({ type: 'GeometryCollection', geometries: geometries }, properties, options); } /** * 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 _turf_helpers_main_es_round(num, precision) { if (num === undefined || num === null || isNaN(num)) throw new Error('num is required'); 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; } /** * 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 _turf_helpers_main_es_radiansToLength(radians, units) { if (radians === undefined || radians === null) throw new Error('radians is required'); if (units && typeof units !== 'string') throw new Error('units must be a string'); var factor = _turf_helpers_main_es_factors[units || 'kilometers']; if (!factor) throw new Error(units + ' units is invalid'); return radians * factor; } /** * 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 _turf_helpers_main_es_lengthToRadians(distance, units) { if (distance === undefined || distance === null) throw new Error('distance is required'); if (units && typeof units !== 'string') throw new Error('units must be a string'); var factor = _turf_helpers_main_es_factors[units || 'kilometers']; if (!factor) throw new Error(units + ' units is invalid'); return distance / factor; } /** * 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 _turf_helpers_main_es_lengthToDegrees(distance, units) { return _turf_helpers_main_es_radiansToDegrees(_turf_helpers_main_es_lengthToRadians(distance, units)); } /** * 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 _turf_helpers_main_es_bearingToAzimuth(bearing) { if (bearing === null || bearing === undefined) throw new Error('bearing is required'); var angle = bearing % 360; if (angle < 0) angle += 360; return angle; } /** * Converts an angle in radians to degrees * * @name radiansToDegrees * @param {number} radians angle in radians * @returns {number} degrees between 0 and 360 degrees */ function _turf_helpers_main_es_radiansToDegrees(radians) { if (radians === null || radians === undefined) throw new Error('radians is required'); var degrees = radians % (2 * Math.PI); return degrees * 180 / Math.PI; } /** * Converts an angle in degrees to radians * * @name degreesToRadians * @param {number} degrees angle between 0 and 360 degrees * @returns {number} angle in radians */ function _turf_helpers_main_es_degreesToRadians(degrees) { if (degrees === null || degrees === undefined) throw new Error('degrees is required'); var radians = degrees % 360; return radians * Math.PI / 180; } /** * 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 {string} originalUnit of the length * @param {string} [finalUnit='kilometers'] returned unit * @returns {number} the converted length */ function _turf_helpers_main_es_convertLength(length, originalUnit, finalUnit) { if (length === null || length === undefined) throw new Error('length is required'); if (!(length >= 0)) throw new Error('length must be a positive number'); return _turf_helpers_main_es_radiansToLength(_turf_helpers_main_es_lengthToRadians(length, originalUnit), finalUnit || 'kilometers'); } /** * 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 {string} [originalUnit='meters'] of the distance * @param {string} [finalUnit='kilometers'] returned unit * @returns {number} the converted distance */ function _turf_helpers_main_es_convertArea(area, originalUnit, finalUnit) { if (area === null || area === undefined) throw new Error('area is required'); if (!(area >= 0)) throw new Error('area must be a positive number'); var startFactor = _turf_helpers_main_es_areaFactors[originalUnit || 'meters']; if (!startFactor) throw new Error('invalid original units'); var finalFactor = _turf_helpers_main_es_areaFactors[finalUnit || 'kilometers']; if (!finalFactor) throw new Error('invalid final units'); return (area / startFactor) * finalFactor; } /** * isNumber * * @param {*} num Number to validate * @returns {boolean} true/false * @example * turf.isNumber(123) * //=true * turf.isNumber('foo') * //=false */ function node_modules_turf_helpers_main_es_isNumber(num) { return !isNaN(num) && num !== null && !Array.isArray(num); } /** * isObject * * @param {*} input variable to validate * @returns {boolean} true/false * @example * turf.isObject({elevation: 10}) * //=true * turf.isObject('foo') * //=false */ function node_modules_turf_helpers_main_es_isObject(input) { return (!!input) && (input.constructor === Object); } /** * Validate BBox * * @private * @param {Array} 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 _turf_helpers_main_es_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 (!node_modules_turf_helpers_main_es_isNumber(num)) throw new Error('bbox must only contain numbers'); }); } /** * 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 _turf_helpers_main_es_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'); } // Deprecated methods function _turf_helpers_main_es_radians2degrees() { throw new Error('method has been renamed to `radiansToDegrees`'); } function _turf_helpers_main_es_degrees2radians() { throw new Error('method has been renamed to `degreesToRadians`'); } function _turf_helpers_main_es_distanceToDegrees() { throw new Error('method has been renamed to `lengthToDegrees`'); } function _turf_helpers_main_es_distanceToRadians() { throw new Error('method has been renamed to `lengthToRadians`'); } function _turf_helpers_main_es_radiansToDistance() { throw new Error('method has been renamed to `radiansToLength`'); } function _turf_helpers_main_es_bearingToAngle() { throw new Error('method has been renamed to `bearingToAzimuth`'); } function _turf_helpers_main_es_convertDistance() { throw new Error('method has been renamed to `convertLength`'); } ;// CONCATENATED MODULE: ./node_modules/@turf/invariant/main.es.js /** * Unwrap a coordinate from a Point Feature, Geometry or a single coordinate. * * @name getCoord * @param {Array|Geometry|Feature} coord GeoJSON Point or an Array of numbers * @returns {Array} coordinates * @example * var pt = turf.point([10, 10]); * * var coord = turf.getCoord(pt); * //= [10, 10] */ function getCoord(coord) { if (!coord) throw new Error('coord is required'); if (coord.type === 'Feature' && coord.geometry !== null && coord.geometry.type === 'Point') return coord.geometry.coordinates; if (coord.type === 'Point') return coord.coordinates; if (Array.isArray(coord) && coord.length >= 2 && coord[0].length === undefined && coord[1].length === undefined) return coord; throw new Error('coord must be GeoJSON Point or an Array of numbers'); } /** * Unwrap coordinates from a Feature, Geometry Object or an Array * * @name getCoords * @param {Array|Geometry|Feature} coords Feature, Geometry Object or an Array * @returns {Array} coordinates * @example * var poly = turf.polygon([[[119.32, -8.7], [119.55, -8.69], [119.51, -8.54], [119.32, -8.7]]]); * * var coords = turf.getCoords(poly); * //= [[[119.32, -8.7], [119.55, -8.69], [119.51, -8.54], [119.32, -8.7]]] */ function getCoords(coords) { if (!coords) throw new Error('coords is required'); // Feature if (coords.type === 'Feature' && coords.geometry !== null) return coords.geometry.coordinates; // Geometry if (coords.coordinates) return coords.coordinates; // Array of numbers if (Array.isArray(coords)) return coords; throw new Error('coords must be GeoJSON Feature, Geometry Object or an Array'); } /** * Checks if coordinates contains a number * * @name containsNumber * @param {Array} coordinates GeoJSON Coordinates * @returns {boolean} true if Array contains a number */ function containsNumber(coordinates) { if (coordinates.length > 1 && isNumber(coordinates[0]) && isNumber(coordinates[1])) { return true; } if (Array.isArray(coordinates[0]) && coordinates[0].length) { return containsNumber(coordinates[0]); } throw new Error('coordinates must only contain numbers'); } /** * Enforce expectations about types of GeoJSON objects for Turf. * * @name geojsonType * @param {GeoJSON} value any GeoJSON object * @param {string} type expected GeoJSON type * @param {string} name name of calling function * @throws {Error} if value is not the expected type. */ function geojsonType(value, type, name) { if (!type || !name) throw new Error('type and name required'); if (!value || value.type !== type) { throw new Error('Invalid input to ' + name + ': must be a ' + type + ', given ' + value.type); } } /** * Enforce expectations about types of {@link Feature} inputs for Turf. * Internally this uses {@link geojsonType} to judge geometry types. * * @name featureOf * @param {Feature} feature a feature with an expected geometry type * @param {string} type expected GeoJSON type * @param {string} name name of calling function * @throws {Error} error if value is not the expected type. */ function featureOf(feature, type, name) { if (!feature) throw new Error('No feature passed'); if (!name) throw new Error('.featureOf() requires a name'); if (!feature || feature.type !== 'Feature' || !feature.geometry) { throw new Error('Invalid input to ' + name + ', Feature with geometry required'); } if (!feature.geometry || feature.geometry.type !== type) { throw new Error('Invalid input to ' + name + ': must be a ' + type + ', given ' + feature.geometry.type); } } /** * Enforce expectations about types of {@link FeatureCollection} inputs for Turf. * Internally this uses {@link geojsonType} to judge geometry types. * * @name collectionOf * @param {FeatureCollection} featureCollection a FeatureCollection for which features will be judged * @param {string} type expected GeoJSON type * @param {string} name name of calling function * @throws {Error} if value is not the expected type. */ function collectionOf(featureCollection, type, name) { if (!featureCollection) throw new Error('No featureCollection passed'); if (!name) throw new Error('.collectionOf() requires a name'); if (!featureCollection || featureCollection.type !== 'FeatureCollection') { throw new Error('Invalid input to ' + name + ', FeatureCollection required'); } for (var i = 0; i < featureCollection.features.length; i++) { var feature = featureCollection.features[i]; if (!feature || feature.type !== 'Feature' || !feature.geometry) { throw new Error('Invalid input to ' + name + ', Feature with geometry required'); } if (!feature.geometry || feature.geometry.type !== type) { throw new Error('Invalid input to ' + name + ': must be a ' + type + ', given ' + feature.geometry.type); } } } /** * Get Geometry from Feature or Geometry Object * * @param {Feature|Geometry} geojson GeoJSON Feature or Geometry Object * @returns {Geometry|null} GeoJSON Geometry Object * @throws {Error} if geojson is not a Feature or Geometry Object * @example * var point = { * "type": "Feature", * "properties": {}, * "geometry": { * "type": "Point", * "coordinates": [110, 40] * } * } * var geom = turf.getGeom(point) * //={"type": "Point", "coordinates": [110, 40]} */ function getGeom(geojson) { if (!geojson) throw new Error('geojson is required'); if (geojson.geometry !== undefined) return geojson.geometry; if (geojson.coordinates || geojson.geometries) return geojson; throw new Error('geojson must be a valid Feature or Geometry Object'); } /** * Get Geometry Type from Feature or Geometry Object * * @throws {Error} **DEPRECATED** in v5.0.0 in favor of getType */ function getGeomType() { throw new Error('invariant.getGeomType has been deprecated in v5.0 in favor of invariant.getType'); } /** * Get GeoJSON object's type, Geometry type is prioritize. * * @param {GeoJSON} geojson GeoJSON object * @param {string} [name="geojson"] name of the variable to display in error message * @returns {string} GeoJSON type * @example * var point = { * "type": "Feature", * "properties": {}, * "geometry": { * "type": "Point", * "coordinates": [110, 40] * } * } * var geom = turf.getType(point) * //="Point" */ function getType(geojson, name) { if (!geojson) throw new Error((name || 'geojson') + ' is required'); // GeoJSON Feature & GeometryCollection if (geojson.geometry && geojson.geometry.type) return geojson.geometry.type; // GeoJSON Geometry & FeatureCollection if (geojson.type) return geojson.type; throw new Error((name || 'geojson') + ' is invalid'); } ;// CONCATENATED MODULE: ./node_modules/@turf/rhumb-bearing/node_modules/@turf/helpers/main.es.js /** * Earth Radius used with the Harvesine formula and approximates using a spherical (non-ellipsoid) Earth. */ var node_modules_turf_helpers_main_es_earthRadius = 6371008.8; /** * Unit of measurement factors using a spherical (non-ellipsoid) earth radius. */ var node_modules_turf_helpers_main_es_factors = { meters: node_modules_turf_helpers_main_es_earthRadius, metres: node_modules_turf_helpers_main_es_earthRadius, millimeters: node_modules_turf_helpers_main_es_earthRadius * 1000, millimetres: node_modules_turf_helpers_main_es_earthRadius * 1000, centimeters: node_modules_turf_helpers_main_es_earthRadius * 100, centimetres: node_modules_turf_helpers_main_es_earthRadius * 100, kilometers: node_modules_turf_helpers_main_es_earthRadius / 1000, kilometres: node_modules_turf_helpers_main_es_earthRadius / 1000, miles: node_modules_turf_helpers_main_es_earthRadius / 1609.344, nauticalmiles: node_modules_turf_helpers_main_es_earthRadius / 1852, inches: node_modules_turf_helpers_main_es_earthRadius * 39.370, yards: node_modules_turf_helpers_main_es_earthRadius / 1.0936, feet: node_modules_turf_helpers_main_es_earthRadius * 3.28084, radians: 1, degrees: node_modules_turf_helpers_main_es_earthRadius / 111325, }; /** * Units of measurement factors based on 1 meter. */ var node_modules_turf_helpers_main_es_unitsFactors = { meters: 1, metres: 1, millimeters: 1000, millimetres: 1000, centimeters: 100, centimetres: 100, kilometers: 1 / 1000, kilometres: 1 / 1000, miles: 1 / 1609.344, nauticalmiles: 1 / 1852, inches: 39.370, yards: 1 / 1.0936, feet: 3.28084, radians: 1 / node_modules_turf_helpers_main_es_earthRadius, degrees: 1 / 111325, }; /** * Area of measurement factors based on 1 square meter. */ var node_modules_turf_helpers_main_es_areaFactors = { meters: 1, metres: 1, millimeters: 1000000, millimetres: 1000000, centimeters: 10000, centimetres: 10000, kilometers: 0.000001, kilometres: 0.000001, acres: 0.000247105, miles: 3.86e-7, yards: 1.195990046, feet: 10.763910417, inches: 1550.003100006 }; /** * 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} [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 rhumb_bearing_node_modules_turf_helpers_main_es_feature(geometry, properties, options) { // Optional Parameters options = options || {}; if (!rhumb_bearing_node_modules_turf_helpers_main_es_isObject(options)) throw new Error('options is invalid'); var bbox = options.bbox; var id = options.id; // Validation if (geometry === undefined) throw new Error('geometry is required'); if (properties && properties.constructor !== Object) throw new Error('properties must be an Object'); if (bbox) node_modules_turf_helpers_main_es_validateBBox(bbox); if (id) node_modules_turf_helpers_main_es_validateId(id); // Main var feat = {type: 'Feature'}; if (id) feat.id = id; if (bbox) feat.bbox = bbox; feat.properties = properties || {}; feat.geometry = geometry; return feat; } /** * 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} coordinates Coordinates * @param {Object} [options={}] Optional Parameters * @param {Array} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Geometry * @returns {Geometry} a GeoJSON Geometry * @example * var type = 'Point'; * var coordinates = [110, 50]; * * var geometry = turf.geometry(type, coordinates); * * //=geometry */ function node_modules_turf_helpers_main_es_geometry(type, coordinates, options) { // Optional Parameters options = options || {}; if (!rhumb_bearing_node_modules_turf_helpers_main_es_isObject(options)) throw new Error('options is invalid'); var bbox = options.bbox; // Validation if (!type) throw new Error('type is required'); if (!coordinates) throw new Error('coordinates is required'); if (!Array.isArray(coordinates)) throw new Error('coordinates must be an Array'); if (bbox) node_modules_turf_helpers_main_es_validateBBox(bbox); // Main var geom; switch (type) { case 'Point': geom = rhumb_bearing_node_modules_turf_helpers_main_es_point(coordinates).geometry; break; case 'LineString': geom = rhumb_bearing_node_modules_turf_helpers_main_es_lineString(coordinates).geometry; break; case 'Polygon': geom = node_modules_turf_helpers_main_es_polygon(coordinates).geometry; break; case 'MultiPoint': geom = node_modules_turf_helpers_main_es_multiPoint(coordinates).geometry; break; case 'MultiLineString': geom = node_modules_turf_helpers_main_es_multiLineString(coordinates).geometry; break; case 'MultiPolygon': geom = node_modules_turf_helpers_main_es_multiPolygon(coordinates).geometry; break; default: throw new Error(type + ' is invalid'); } if (bbox) geom.bbox = bbox; return geom; } /** * Creates a {@link Point} {@link Feature} from a Position. * * @name point * @param {Array} 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} [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 Point feature * @example * var point = turf.point([-75.343, 39.984]); * * //=point */ function rhumb_bearing_node_modules_turf_helpers_main_es_point(coordinates, properties, options) { if (!coordinates) throw new Error('coordinates is required'); if (!Array.isArray(coordinates)) throw new Error('coordinates must be an Array'); if (coordinates.length < 2) throw new Error('coordinates must be at least 2 numbers long'); if (!rhumb_bearing_node_modules_turf_helpers_main_es_isNumber(coordinates[0]) || !rhumb_bearing_node_modules_turf_helpers_main_es_isNumber(coordinates[1])) throw new Error('coordinates must contain numbers'); return rhumb_bearing_node_modules_turf_helpers_main_es_feature({ type: 'Point', coordinates: coordinates }, properties, options); } /** * Creates a {@link Point} {@link FeatureCollection} from an Array of Point coordinates. * * @name points * @param {Array>} coordinates an array of Points * @param {Object} [properties={}] Translate these properties to each Feature * @param {Object} [options={}] Optional Parameters * @param {Array} [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 Feature * @example * var points = turf.points([ * [-75, 39], * [-80, 45], * [-78, 50] * ]); * * //=points */ function node_modules_turf_helpers_main_es_points(coordinates, properties, options) { if (!coordinates) throw new Error('coordinates is required'); if (!Array.isArray(coordinates)) throw new Error('coordinates must be an Array'); return node_modules_turf_helpers_main_es_featureCollection(coordinates.map(function (coords) { return rhumb_bearing_node_modules_turf_helpers_main_es_point(coords, properties); }), options); } /** * Creates a {@link Polygon} {@link Feature} from an Array of LinearRings. * * @name polygon * @param {Array>>} 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} [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 Feature * @example * var polygon = turf.polygon([[[-5, 52], [-4, 56], [-2, 51], [-7, 54], [-5, 52]]], { name: 'poly1' }); * * //=polygon */ function node_modules_turf_helpers_main_es_polygon(coordinates, properties, options) { if (!coordinates) throw new Error('coordinates is required'); for (var i = 0; i < coordinates.length; i++) { var ring = coordinates[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 (i === 0 && j === 0 && !rhumb_bearing_node_modules_turf_helpers_main_es_isNumber(ring[0][0]) || !rhumb_bearing_node_modules_turf_helpers_main_es_isNumber(ring[0][1])) throw new Error('coordinates must contain numbers'); if (ring[ring.length - 1][j] !== ring[0][j]) { throw new Error('First and last Position are not equivalent.'); } } } return rhumb_bearing_node_modules_turf_helpers_main_es_feature({ type: 'Polygon', coordinates: coordinates }, properties, options); } /** * Creates a {@link Polygon} {@link FeatureCollection} from an Array of Polygon coordinates. * * @name polygons * @param {Array>>>} 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} [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 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 node_modules_turf_helpers_main_es_polygons(coordinates, properties, options) { if (!coordinates) throw new Error('coordinates is required'); if (!Array.isArray(coordinates)) throw new Error('coordinates must be an Array'); return node_modules_turf_helpers_main_es_featureCollection(coordinates.map(function (coords) { return node_modules_turf_helpers_main_es_polygon(coords, properties); }), options); } /** * Creates a {@link LineString} {@link Feature} from an Array of Positions. * * @name lineString * @param {Array>} 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} [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 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 rhumb_bearing_node_modules_turf_helpers_main_es_lineString(coordinates, properties, options) { if (!coordinates) throw new Error('coordinates is required'); if (coordinates.length < 2) throw new Error('coordinates must be an array of two or more positions'); // Check if first point of LineString contains two numbers if (!rhumb_bearing_node_modules_turf_helpers_main_es_isNumber(coordinates[0][1]) || !rhumb_bearing_node_modules_turf_helpers_main_es_isNumber(coordinates[0][1])) throw new Error('coordinates must contain numbers'); return rhumb_bearing_node_modules_turf_helpers_main_es_feature({ type: 'LineString', coordinates: coordinates }, properties, options); } /** * Creates a {@link LineString} {@link FeatureCollection} from an Array of LineString coordinates. * * @name lineStrings * @param {Array>} 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} [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 FeatureCollection * @example * var linestrings = turf.lineStrings([ * [[-24, 63], [-23, 60], [-25, 65], [-20, 69]], * [[-14, 43], [-13, 40], [-15, 45], [-10, 49]] * ]); * * //=linestrings */ function node_modules_turf_helpers_main_es_lineStrings(coordinates, properties, options) { if (!coordinates) throw new Error('coordinates is required'); if (!Array.isArray(coordinates)) throw new Error('coordinates must be an Array'); return node_modules_turf_helpers_main_es_featureCollection(coordinates.map(function (coords) { return rhumb_bearing_node_modules_turf_helpers_main_es_lineString(coords, properties); }), options); } /** * 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} [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 node_modules_turf_helpers_main_es_featureCollection(features, options) { // Optional Parameters options = options || {}; if (!rhumb_bearing_node_modules_turf_helpers_main_es_isObject(options)) throw new Error('options is invalid'); var bbox = options.bbox; var id = options.id; // Validation if (!features) throw new Error('No features passed'); if (!Array.isArray(features)) throw new Error('features must be an Array'); if (bbox) node_modules_turf_helpers_main_es_validateBBox(bbox); if (id) node_modules_turf_helpers_main_es_validateId(id); // Main var fc = {type: 'FeatureCollection'}; if (id) fc.id = id; if (bbox) fc.bbox = bbox; fc.features = features; return fc; } /** * Creates a {@link Feature} based on a * coordinate array. Properties can be added optionally. * * @name multiLineString * @param {Array>>} 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} [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 MultiLineString feature * @throws {Error} if no coordinates are passed * @example * var multiLine = turf.multiLineString([[[0,0],[10,10]]]); * * //=multiLine */ function node_modules_turf_helpers_main_es_multiLineString(coordinates, properties, options) { if (!coordinates) throw new Error('coordinates is required'); return rhumb_bearing_node_modules_turf_helpers_main_es_feature({ type: 'MultiLineString', coordinates: coordinates }, properties, options); } /** * Creates a {@link Feature} based on a * coordinate array. Properties can be added optionally. * * @name multiPoint * @param {Array>} 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} [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 MultiPoint feature * @throws {Error} if no coordinates are passed * @example * var multiPt = turf.multiPoint([[0,0],[10,10]]); * * //=multiPt */ function node_modules_turf_helpers_main_es_multiPoint(coordinates, properties, options) { if (!coordinates) throw new Error('coordinates is required'); return rhumb_bearing_node_modules_turf_helpers_main_es_feature({ type: 'MultiPoint', coordinates: coordinates }, properties, options); } /** * Creates a {@link Feature} based on a * coordinate array. Properties can be added optionally. * * @name multiPolygon * @param {Array>>>} 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} [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 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 node_modules_turf_helpers_main_es_multiPolygon(coordinates, properties, options) { if (!coordinates) throw new Error('coordinates is required'); return rhumb_bearing_node_modules_turf_helpers_main_es_feature({ type: 'MultiPolygon', coordinates: coordinates }, properties, options); } /** * Creates a {@link Feature} based on a * coordinate array. Properties can be added optionally. * * @name geometryCollection * @param {Array} 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} [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 GeometryCollection Feature * @example * var pt = { * "type": "Point", * "coordinates": [100, 0] * }; * var line = { * "type": "LineString", * "coordinates": [ [101, 0], [102, 1] ] * }; * var collection = turf.geometryCollection([pt, line]); * * //=collection */ function node_modules_turf_helpers_main_es_geometryCollection(geometries, properties, options) { if (!geometries) throw new Error('geometries is required'); if (!Array.isArray(geometries)) throw new Error('geometries must be an Array'); return rhumb_bearing_node_modules_turf_helpers_main_es_feature({ type: 'GeometryCollection', geometries: geometries }, properties, options); } /** * 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 node_modules_turf_helpers_main_es_round(num, precision) { if (num === undefined || num === null || isNaN(num)) throw new Error('num is required'); 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; } /** * 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 node_modules_turf_helpers_main_es_radiansToLength(radians, units) { if (radians === undefined || radians === null) throw new Error('radians is required'); if (units && typeof units !== 'string') throw new Error('units must be a string'); var factor = node_modules_turf_helpers_main_es_factors[units || 'kilometers']; if (!factor) throw new Error(units + ' units is invalid'); return radians * factor; } /** * 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 node_modules_turf_helpers_main_es_lengthToRadians(distance, units) { if (distance === undefined || distance === null) throw new Error('distance is required'); if (units && typeof units !== 'string') throw new Error('units must be a string'); var factor = node_modules_turf_helpers_main_es_factors[units || 'kilometers']; if (!factor) throw new Error(units + ' units is invalid'); return distance / factor; } /** * 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 node_modules_turf_helpers_main_es_lengthToDegrees(distance, units) { return node_modules_turf_helpers_main_es_radiansToDegrees(node_modules_turf_helpers_main_es_lengthToRadians(distance, units)); } /** * 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 node_modules_turf_helpers_main_es_bearingToAzimuth(bearing) { if (bearing === null || bearing === undefined) throw new Error('bearing is required'); var angle = bearing % 360; if (angle < 0) angle += 360; return angle; } /** * Converts an angle in radians to degrees * * @name radiansToDegrees * @param {number} radians angle in radians * @returns {number} degrees between 0 and 360 degrees */ function node_modules_turf_helpers_main_es_radiansToDegrees(radians) { if (radians === null || radians === undefined) throw new Error('radians is required'); var degrees = radians % (2 * Math.PI); return degrees * 180 / Math.PI; } /** * Converts an angle in degrees to radians * * @name degreesToRadians * @param {number} degrees angle between 0 and 360 degrees * @returns {number} angle in radians */ function node_modules_turf_helpers_main_es_degreesToRadians(degrees) { if (degrees === null || degrees === undefined) throw new Error('degrees is required'); var radians = degrees % 360; return radians * Math.PI / 180; } /** * 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 {string} originalUnit of the length * @param {string} [finalUnit='kilometers'] returned unit * @returns {number} the converted length */ function node_modules_turf_helpers_main_es_convertLength(length, originalUnit, finalUnit) { if (length === null || length === undefined) throw new Error('length is required'); if (!(length >= 0)) throw new Error('length must be a positive number'); return node_modules_turf_helpers_main_es_radiansToLength(node_modules_turf_helpers_main_es_lengthToRadians(length, originalUnit), finalUnit || 'kilometers'); } /** * 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 {string} [originalUnit='meters'] of the distance * @param {string} [finalUnit='kilometers'] returned unit * @returns {number} the converted distance */ function node_modules_turf_helpers_main_es_convertArea(area, originalUnit, finalUnit) { if (area === null || area === undefined) throw new Error('area is required'); if (!(area >= 0)) throw new Error('area must be a positive number'); var startFactor = node_modules_turf_helpers_main_es_areaFactors[originalUnit || 'meters']; if (!startFactor) throw new Error('invalid original units'); var finalFactor = node_modules_turf_helpers_main_es_areaFactors[finalUnit || 'kilometers']; if (!finalFactor) throw new Error('invalid final units'); return (area / startFactor) * finalFactor; } /** * isNumber * * @param {*} num Number to validate * @returns {boolean} true/false * @example * turf.isNumber(123) * //=true * turf.isNumber('foo') * //=false */ function rhumb_bearing_node_modules_turf_helpers_main_es_isNumber(num) { return !isNaN(num) && num !== null && !Array.isArray(num); } /** * isObject * * @param {*} input variable to validate * @returns {boolean} true/false * @example * turf.isObject({elevation: 10}) * //=true * turf.isObject('foo') * //=false */ function rhumb_bearing_node_modules_turf_helpers_main_es_isObject(input) { return (!!input) && (input.constructor === Object); } /** * Validate BBox * * @private * @param {Array} 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 node_modules_turf_helpers_main_es_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 (!rhumb_bearing_node_modules_turf_helpers_main_es_isNumber(num)) throw new Error('bbox must only contain numbers'); }); } /** * 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 node_modules_turf_helpers_main_es_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'); } // Deprecated methods function node_modules_turf_helpers_main_es_radians2degrees() { throw new Error('method has been renamed to `radiansToDegrees`'); } function node_modules_turf_helpers_main_es_degrees2radians() { throw new Error('method has been renamed to `degreesToRadians`'); } function node_modules_turf_helpers_main_es_distanceToDegrees() { throw new Error('method has been renamed to `lengthToDegrees`'); } function node_modules_turf_helpers_main_es_distanceToRadians() { throw new Error('method has been renamed to `lengthToRadians`'); } function node_modules_turf_helpers_main_es_radiansToDistance() { throw new Error('method has been renamed to `radiansToLength`'); } function node_modules_turf_helpers_main_es_bearingToAngle() { throw new Error('method has been renamed to `bearingToAzimuth`'); } function node_modules_turf_helpers_main_es_convertDistance() { throw new Error('method has been renamed to `convertLength`'); } ;// CONCATENATED MODULE: ./node_modules/@turf/rhumb-bearing/main.es.js // https://en.wikipedia.org/wiki/Rhumb_line /** * Takes two {@link Point|points} and finds the bearing angle between them along a Rhumb line * i.e. the angle measured in degrees start the north line (0 degrees) * * @name rhumbBearing * @param {Coord} start starting Point * @param {Coord} end ending Point * @param {Object} [options] Optional parameters * @param {boolean} [options.final=false] calculates the final bearing if true * @returns {number} bearing from north in decimal degrees, between -180 and 180 degrees (positive clockwise) * @example * var point1 = turf.point([-75.343, 39.984], {"marker-color": "#F00"}); * var point2 = turf.point([-75.534, 39.123], {"marker-color": "#00F"}); * * var bearing = turf.rhumbBearing(point1, point2); * * //addToMap * var addToMap = [point1, point2]; * point1.properties.bearing = bearing; * point2.properties.bearing = bearing; */ function rhumbBearing(start, end, options) { // Optional parameters options = options || {}; if (!rhumb_bearing_node_modules_turf_helpers_main_es_isObject(options)) throw new Error('options is invalid'); var final = options.final; // validation if (!start) throw new Error('start point is required'); if (!end) throw new Error('end point is required'); var bear360; if (final) bear360 = calculateRhumbBearing(getCoord(end), getCoord(start)); else bear360 = calculateRhumbBearing(getCoord(start), getCoord(end)); var bear180 = (bear360 > 180) ? -(360 - bear360) : bear360; return bear180; } /** * Returns the bearing from ‘this’ point to destination point along a rhumb line. * Adapted from Geodesy: https://github.com/chrisveness/geodesy/blob/master/latlon-spherical.js * * @private * @param {Array} from - origin point. * @param {Array} to - destination point. * @returns {number} Bearing in degrees from north. * @example * var p1 = new LatLon(51.127, 1.338); * var p2 = new LatLon(50.964, 1.853); * var d = p1.rhumbBearingTo(p2); // 116.7 m */ function calculateRhumbBearing(from, to) { // φ => phi // Δλ => deltaLambda // Δψ => deltaPsi // θ => theta var phi1 = node_modules_turf_helpers_main_es_degreesToRadians(from[1]); var phi2 = node_modules_turf_helpers_main_es_degreesToRadians(to[1]); var deltaLambda = node_modules_turf_helpers_main_es_degreesToRadians((to[0] - from[0])); // if deltaLambdaon over 180° take shorter rhumb line across the anti-meridian: if (deltaLambda > Math.PI) deltaLambda -= 2 * Math.PI; if (deltaLambda < -Math.PI) deltaLambda += 2 * Math.PI; var deltaPsi = Math.log(Math.tan(phi2 / 2 + Math.PI / 4) / Math.tan(phi1 / 2 + Math.PI / 4)); var theta = Math.atan2(deltaLambda, deltaPsi); return (node_modules_turf_helpers_main_es_radiansToDegrees(theta) + 360) % 360; } /* harmony default export */ var rhumb_bearing_main_es = (rhumbBearing); ;// CONCATENATED MODULE: ./node_modules/@turf/rhumb-distance/node_modules/@turf/helpers/main.es.js /** * Earth Radius used with the Harvesine formula and approximates using a spherical (non-ellipsoid) Earth. */ var rhumb_distance_node_modules_turf_helpers_main_es_earthRadius = 6371008.8; /** * Unit of measurement factors using a spherical (non-ellipsoid) earth radius. */ var rhumb_distance_node_modules_turf_helpers_main_es_factors = { meters: rhumb_distance_node_modules_turf_helpers_main_es_earthRadius, metres: rhumb_distance_node_modules_turf_helpers_main_es_earthRadius, millimeters: rhumb_distance_node_modules_turf_helpers_main_es_earthRadius * 1000, millimetres: rhumb_distance_node_modules_turf_helpers_main_es_earthRadius * 1000, centimeters: rhumb_distance_node_modules_turf_helpers_main_es_earthRadius * 100, centimetres: rhumb_distance_node_modules_turf_helpers_main_es_earthRadius * 100, kilometers: rhumb_distance_node_modules_turf_helpers_main_es_earthRadius / 1000, kilometres: rhumb_distance_node_modules_turf_helpers_main_es_earthRadius / 1000, miles: rhumb_distance_node_modules_turf_helpers_main_es_earthRadius / 1609.344, nauticalmiles: rhumb_distance_node_modules_turf_helpers_main_es_earthRadius / 1852, inches: rhumb_distance_node_modules_turf_helpers_main_es_earthRadius * 39.370, yards: rhumb_distance_node_modules_turf_helpers_main_es_earthRadius / 1.0936, feet: rhumb_distance_node_modules_turf_helpers_main_es_earthRadius * 3.28084, radians: 1, degrees: rhumb_distance_node_modules_turf_helpers_main_es_earthRadius / 111325, }; /** * Units of measurement factors based on 1 meter. */ var rhumb_distance_node_modules_turf_helpers_main_es_unitsFactors = { meters: 1, metres: 1, millimeters: 1000, millimetres: 1000, centimeters: 100, centimetres: 100, kilometers: 1 / 1000, kilometres: 1 / 1000, miles: 1 / 1609.344, nauticalmiles: 1 / 1852, inches: 39.370, yards: 1 / 1.0936, feet: 3.28084, radians: 1 / rhumb_distance_node_modules_turf_helpers_main_es_earthRadius, degrees: 1 / 111325, }; /** * Area of measurement factors based on 1 square meter. */ var rhumb_distance_node_modules_turf_helpers_main_es_areaFactors = { meters: 1, metres: 1, millimeters: 1000000, millimetres: 1000000, centimeters: 10000, centimetres: 10000, kilometers: 0.000001, kilometres: 0.000001, acres: 0.000247105, miles: 3.86e-7, yards: 1.195990046, feet: 10.763910417, inches: 1550.003100006 }; /** * 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} [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 rhumb_distance_node_modules_turf_helpers_main_es_feature(geometry, properties, options) { // Optional Parameters options = options || {}; if (!rhumb_distance_node_modules_turf_helpers_main_es_isObject(options)) throw new Error('options is invalid'); var bbox = options.bbox; var id = options.id; // Validation if (geometry === undefined) throw new Error('geometry is required'); if (properties && properties.constructor !== Object) throw new Error('properties must be an Object'); if (bbox) rhumb_distance_node_modules_turf_helpers_main_es_validateBBox(bbox); if (id) rhumb_distance_node_modules_turf_helpers_main_es_validateId(id); // Main var feat = {type: 'Feature'}; if (id) feat.id = id; if (bbox) feat.bbox = bbox; feat.properties = properties || {}; feat.geometry = geometry; return feat; } /** * 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} coordinates Coordinates * @param {Object} [options={}] Optional Parameters * @param {Array} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Geometry * @returns {Geometry} a GeoJSON Geometry * @example * var type = 'Point'; * var coordinates = [110, 50]; * * var geometry = turf.geometry(type, coordinates); * * //=geometry */ function rhumb_distance_node_modules_turf_helpers_main_es_geometry(type, coordinates, options) { // Optional Parameters options = options || {}; if (!rhumb_distance_node_modules_turf_helpers_main_es_isObject(options)) throw new Error('options is invalid'); var bbox = options.bbox; // Validation if (!type) throw new Error('type is required'); if (!coordinates) throw new Error('coordinates is required'); if (!Array.isArray(coordinates)) throw new Error('coordinates must be an Array'); if (bbox) rhumb_distance_node_modules_turf_helpers_main_es_validateBBox(bbox); // Main var geom; switch (type) { case 'Point': geom = rhumb_distance_node_modules_turf_helpers_main_es_point(coordinates).geometry; break; case 'LineString': geom = rhumb_distance_node_modules_turf_helpers_main_es_lineString(coordinates).geometry; break; case 'Polygon': geom = rhumb_distance_node_modules_turf_helpers_main_es_polygon(coordinates).geometry; break; case 'MultiPoint': geom = rhumb_distance_node_modules_turf_helpers_main_es_multiPoint(coordinates).geometry; break; case 'MultiLineString': geom = rhumb_distance_node_modules_turf_helpers_main_es_multiLineString(coordinates).geometry; break; case 'MultiPolygon': geom = rhumb_distance_node_modules_turf_helpers_main_es_multiPolygon(coordinates).geometry; break; default: throw new Error(type + ' is invalid'); } if (bbox) geom.bbox = bbox; return geom; } /** * Creates a {@link Point} {@link Feature} from a Position. * * @name point * @param {Array} 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} [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 Point feature * @example * var point = turf.point([-75.343, 39.984]); * * //=point */ function rhumb_distance_node_modules_turf_helpers_main_es_point(coordinates, properties, options) { if (!coordinates) throw new Error('coordinates is required'); if (!Array.isArray(coordinates)) throw new Error('coordinates must be an Array'); if (coordinates.length < 2) throw new Error('coordinates must be at least 2 numbers long'); if (!rhumb_distance_node_modules_turf_helpers_main_es_isNumber(coordinates[0]) || !rhumb_distance_node_modules_turf_helpers_main_es_isNumber(coordinates[1])) throw new Error('coordinates must contain numbers'); return rhumb_distance_node_modules_turf_helpers_main_es_feature({ type: 'Point', coordinates: coordinates }, properties, options); } /** * Creates a {@link Point} {@link FeatureCollection} from an Array of Point coordinates. * * @name points * @param {Array>} coordinates an array of Points * @param {Object} [properties={}] Translate these properties to each Feature * @param {Object} [options={}] Optional Parameters * @param {Array} [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 Feature * @example * var points = turf.points([ * [-75, 39], * [-80, 45], * [-78, 50] * ]); * * //=points */ function rhumb_distance_node_modules_turf_helpers_main_es_points(coordinates, properties, options) { if (!coordinates) throw new Error('coordinates is required'); if (!Array.isArray(coordinates)) throw new Error('coordinates must be an Array'); return rhumb_distance_node_modules_turf_helpers_main_es_featureCollection(coordinates.map(function (coords) { return rhumb_distance_node_modules_turf_helpers_main_es_point(coords, properties); }), options); } /** * Creates a {@link Polygon} {@link Feature} from an Array of LinearRings. * * @name polygon * @param {Array>>} 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} [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 Feature * @example * var polygon = turf.polygon([[[-5, 52], [-4, 56], [-2, 51], [-7, 54], [-5, 52]]], { name: 'poly1' }); * * //=polygon */ function rhumb_distance_node_modules_turf_helpers_main_es_polygon(coordinates, properties, options) { if (!coordinates) throw new Error('coordinates is required'); for (var i = 0; i < coordinates.length; i++) { var ring = coordinates[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 (i === 0 && j === 0 && !rhumb_distance_node_modules_turf_helpers_main_es_isNumber(ring[0][0]) || !rhumb_distance_node_modules_turf_helpers_main_es_isNumber(ring[0][1])) throw new Error('coordinates must contain numbers'); if (ring[ring.length - 1][j] !== ring[0][j]) { throw new Error('First and last Position are not equivalent.'); } } } return rhumb_distance_node_modules_turf_helpers_main_es_feature({ type: 'Polygon', coordinates: coordinates }, properties, options); } /** * Creates a {@link Polygon} {@link FeatureCollection} from an Array of Polygon coordinates. * * @name polygons * @param {Array>>>} 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} [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 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 rhumb_distance_node_modules_turf_helpers_main_es_polygons(coordinates, properties, options) { if (!coordinates) throw new Error('coordinates is required'); if (!Array.isArray(coordinates)) throw new Error('coordinates must be an Array'); return rhumb_distance_node_modules_turf_helpers_main_es_featureCollection(coordinates.map(function (coords) { return rhumb_distance_node_modules_turf_helpers_main_es_polygon(coords, properties); }), options); } /** * Creates a {@link LineString} {@link Feature} from an Array of Positions. * * @name lineString * @param {Array>} 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} [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 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 rhumb_distance_node_modules_turf_helpers_main_es_lineString(coordinates, properties, options) { if (!coordinates) throw new Error('coordinates is required'); if (coordinates.length < 2) throw new Error('coordinates must be an array of two or more positions'); // Check if first point of LineString contains two numbers if (!rhumb_distance_node_modules_turf_helpers_main_es_isNumber(coordinates[0][1]) || !rhumb_distance_node_modules_turf_helpers_main_es_isNumber(coordinates[0][1])) throw new Error('coordinates must contain numbers'); return rhumb_distance_node_modules_turf_helpers_main_es_feature({ type: 'LineString', coordinates: coordinates }, properties, options); } /** * Creates a {@link LineString} {@link FeatureCollection} from an Array of LineString coordinates. * * @name lineStrings * @param {Array>} 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} [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 FeatureCollection * @example * var linestrings = turf.lineStrings([ * [[-24, 63], [-23, 60], [-25, 65], [-20, 69]], * [[-14, 43], [-13, 40], [-15, 45], [-10, 49]] * ]); * * //=linestrings */ function rhumb_distance_node_modules_turf_helpers_main_es_lineStrings(coordinates, properties, options) { if (!coordinates) throw new Error('coordinates is required'); if (!Array.isArray(coordinates)) throw new Error('coordinates must be an Array'); return rhumb_distance_node_modules_turf_helpers_main_es_featureCollection(coordinates.map(function (coords) { return rhumb_distance_node_modules_turf_helpers_main_es_lineString(coords, properties); }), options); } /** * 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} [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 rhumb_distance_node_modules_turf_helpers_main_es_featureCollection(features, options) { // Optional Parameters options = options || {}; if (!rhumb_distance_node_modules_turf_helpers_main_es_isObject(options)) throw new Error('options is invalid'); var bbox = options.bbox; var id = options.id; // Validation if (!features) throw new Error('No features passed'); if (!Array.isArray(features)) throw new Error('features must be an Array'); if (bbox) rhumb_distance_node_modules_turf_helpers_main_es_validateBBox(bbox); if (id) rhumb_distance_node_modules_turf_helpers_main_es_validateId(id); // Main var fc = {type: 'FeatureCollection'}; if (id) fc.id = id; if (bbox) fc.bbox = bbox; fc.features = features; return fc; } /** * Creates a {@link Feature} based on a * coordinate array. Properties can be added optionally. * * @name multiLineString * @param {Array>>} 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} [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 MultiLineString feature * @throws {Error} if no coordinates are passed * @example * var multiLine = turf.multiLineString([[[0,0],[10,10]]]); * * //=multiLine */ function rhumb_distance_node_modules_turf_helpers_main_es_multiLineString(coordinates, properties, options) { if (!coordinates) throw new Error('coordinates is required'); return rhumb_distance_node_modules_turf_helpers_main_es_feature({ type: 'MultiLineString', coordinates: coordinates }, properties, options); } /** * Creates a {@link Feature} based on a * coordinate array. Properties can be added optionally. * * @name multiPoint * @param {Array>} 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} [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 MultiPoint feature * @throws {Error} if no coordinates are passed * @example * var multiPt = turf.multiPoint([[0,0],[10,10]]); * * //=multiPt */ function rhumb_distance_node_modules_turf_helpers_main_es_multiPoint(coordinates, properties, options) { if (!coordinates) throw new Error('coordinates is required'); return rhumb_distance_node_modules_turf_helpers_main_es_feature({ type: 'MultiPoint', coordinates: coordinates }, properties, options); } /** * Creates a {@link Feature} based on a * coordinate array. Properties can be added optionally. * * @name multiPolygon * @param {Array>>>} 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} [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 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 rhumb_distance_node_modules_turf_helpers_main_es_multiPolygon(coordinates, properties, options) { if (!coordinates) throw new Error('coordinates is required'); return rhumb_distance_node_modules_turf_helpers_main_es_feature({ type: 'MultiPolygon', coordinates: coordinates }, properties, options); } /** * Creates a {@link Feature} based on a * coordinate array. Properties can be added optionally. * * @name geometryCollection * @param {Array} 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} [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 GeometryCollection Feature * @example * var pt = { * "type": "Point", * "coordinates": [100, 0] * }; * var line = { * "type": "LineString", * "coordinates": [ [101, 0], [102, 1] ] * }; * var collection = turf.geometryCollection([pt, line]); * * //=collection */ function rhumb_distance_node_modules_turf_helpers_main_es_geometryCollection(geometries, properties, options) { if (!geometries) throw new Error('geometries is required'); if (!Array.isArray(geometries)) throw new Error('geometries must be an Array'); return rhumb_distance_node_modules_turf_helpers_main_es_feature({ type: 'GeometryCollection', geometries: geometries }, properties, options); } /** * 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 rhumb_distance_node_modules_turf_helpers_main_es_round(num, precision) { if (num === undefined || num === null || isNaN(num)) throw new Error('num is required'); 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; } /** * 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 rhumb_distance_node_modules_turf_helpers_main_es_radiansToLength(radians, units) { if (radians === undefined || radians === null) throw new Error('radians is required'); if (units && typeof units !== 'string') throw new Error('units must be a string'); var factor = rhumb_distance_node_modules_turf_helpers_main_es_factors[units || 'kilometers']; if (!factor) throw new Error(units + ' units is invalid'); return radians * factor; } /** * 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 rhumb_distance_node_modules_turf_helpers_main_es_lengthToRadians(distance, units) { if (distance === undefined || distance === null) throw new Error('distance is required'); if (units && typeof units !== 'string') throw new Error('units must be a string'); var factor = rhumb_distance_node_modules_turf_helpers_main_es_factors[units || 'kilometers']; if (!factor) throw new Error(units + ' units is invalid'); return distance / factor; } /** * 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 rhumb_distance_node_modules_turf_helpers_main_es_lengthToDegrees(distance, units) { return rhumb_distance_node_modules_turf_helpers_main_es_radiansToDegrees(rhumb_distance_node_modules_turf_helpers_main_es_lengthToRadians(distance, units)); } /** * 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 rhumb_distance_node_modules_turf_helpers_main_es_bearingToAzimuth(bearing) { if (bearing === null || bearing === undefined) throw new Error('bearing is required'); var angle = bearing % 360; if (angle < 0) angle += 360; return angle; } /** * Converts an angle in radians to degrees * * @name radiansToDegrees * @param {number} radians angle in radians * @returns {number} degrees between 0 and 360 degrees */ function rhumb_distance_node_modules_turf_helpers_main_es_radiansToDegrees(radians) { if (radians === null || radians === undefined) throw new Error('radians is required'); var degrees = radians % (2 * Math.PI); return degrees * 180 / Math.PI; } /** * Converts an angle in degrees to radians * * @name degreesToRadians * @param {number} degrees angle between 0 and 360 degrees * @returns {number} angle in radians */ function rhumb_distance_node_modules_turf_helpers_main_es_degreesToRadians(degrees) { if (degrees === null || degrees === undefined) throw new Error('degrees is required'); var radians = degrees % 360; return radians * Math.PI / 180; } /** * 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 {string} originalUnit of the length * @param {string} [finalUnit='kilometers'] returned unit * @returns {number} the converted length */ function rhumb_distance_node_modules_turf_helpers_main_es_convertLength(length, originalUnit, finalUnit) { if (length === null || length === undefined) throw new Error('length is required'); if (!(length >= 0)) throw new Error('length must be a positive number'); return rhumb_distance_node_modules_turf_helpers_main_es_radiansToLength(rhumb_distance_node_modules_turf_helpers_main_es_lengthToRadians(length, originalUnit), finalUnit || 'kilometers'); } /** * 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 {string} [originalUnit='meters'] of the distance * @param {string} [finalUnit='kilometers'] returned unit * @returns {number} the converted distance */ function rhumb_distance_node_modules_turf_helpers_main_es_convertArea(area, originalUnit, finalUnit) { if (area === null || area === undefined) throw new Error('area is required'); if (!(area >= 0)) throw new Error('area must be a positive number'); var startFactor = rhumb_distance_node_modules_turf_helpers_main_es_areaFactors[originalUnit || 'meters']; if (!startFactor) throw new Error('invalid original units'); var finalFactor = rhumb_distance_node_modules_turf_helpers_main_es_areaFactors[finalUnit || 'kilometers']; if (!finalFactor) throw new Error('invalid final units'); return (area / startFactor) * finalFactor; } /** * isNumber * * @param {*} num Number to validate * @returns {boolean} true/false * @example * turf.isNumber(123) * //=true * turf.isNumber('foo') * //=false */ function rhumb_distance_node_modules_turf_helpers_main_es_isNumber(num) { return !isNaN(num) && num !== null && !Array.isArray(num); } /** * isObject * * @param {*} input variable to validate * @returns {boolean} true/false * @example * turf.isObject({elevation: 10}) * //=true * turf.isObject('foo') * //=false */ function rhumb_distance_node_modules_turf_helpers_main_es_isObject(input) { return (!!input) && (input.constructor === Object); } /** * Validate BBox * * @private * @param {Array} 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 rhumb_distance_node_modules_turf_helpers_main_es_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 (!rhumb_distance_node_modules_turf_helpers_main_es_isNumber(num)) throw new Error('bbox must only contain numbers'); }); } /** * 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 rhumb_distance_node_modules_turf_helpers_main_es_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'); } // Deprecated methods function rhumb_distance_node_modules_turf_helpers_main_es_radians2degrees() { throw new Error('method has been renamed to `radiansToDegrees`'); } function rhumb_distance_node_modules_turf_helpers_main_es_degrees2radians() { throw new Error('method has been renamed to `degreesToRadians`'); } function rhumb_distance_node_modules_turf_helpers_main_es_distanceToDegrees() { throw new Error('method has been renamed to `lengthToDegrees`'); } function rhumb_distance_node_modules_turf_helpers_main_es_distanceToRadians() { throw new Error('method has been renamed to `lengthToRadians`'); } function rhumb_distance_node_modules_turf_helpers_main_es_radiansToDistance() { throw new Error('method has been renamed to `radiansToLength`'); } function rhumb_distance_node_modules_turf_helpers_main_es_bearingToAngle() { throw new Error('method has been renamed to `bearingToAzimuth`'); } function rhumb_distance_node_modules_turf_helpers_main_es_convertDistance() { throw new Error('method has been renamed to `convertLength`'); } ;// CONCATENATED MODULE: ./node_modules/@turf/rhumb-distance/main.es.js // https://en.wikipedia.org/wiki/Rhumb_line /** * Calculates the distance along a rhumb line between two {@link Point|points} in degrees, radians, * miles, or kilometers. * * @name rhumbDistance * @param {Coord} from origin point * @param {Coord} to destination point * @param {Object} [options] Optional parameters * @param {string} [options.units="kilometers"] can be degrees, radians, miles, or kilometers * @returns {number} distance between the two points * @example * var from = turf.point([-75.343, 39.984]); * var to = turf.point([-75.534, 39.123]); * var options = {units: 'miles'}; * * var distance = turf.rhumbDistance(from, to, options); * * //addToMap * var addToMap = [from, to]; * from.properties.distance = distance; * to.properties.distance = distance; */ function rhumbDistance(from, to, options) { // Optional parameters options = options || {}; if (!rhumb_distance_node_modules_turf_helpers_main_es_isObject(options)) throw new Error('options is invalid'); var units = options.units; // validation if (!from) throw new Error('from point is required'); if (!to) throw new Error('to point is required'); var origin = getCoord(from); var destination = getCoord(to); // compensate the crossing of the 180th meridian (https://macwright.org/2016/09/26/the-180th-meridian.html) // solution from https://github.com/mapbox/mapbox-gl-js/issues/3250#issuecomment-294887678 destination[0] += (destination[0] - origin[0] > 180) ? -360 : (origin[0] - destination[0] > 180) ? 360 : 0; var distanceInMeters = calculateRhumbDistance(origin, destination); var distance = rhumb_distance_node_modules_turf_helpers_main_es_convertLength(distanceInMeters, 'meters', units); return distance; } /** * Returns the distance travelling from ‘this’ point to destination point along a rhumb line. * Adapted from Geodesy: https://github.com/chrisveness/geodesy/blob/master/latlon-spherical.js * * @private * @param {Array} origin point. * @param {Array} destination point. * @param {number} [radius=6371e3] - (Mean) radius of earth (defaults to radius in metres). * @returns {number} Distance in km between this point and destination point (same units as radius). * * @example * var p1 = new LatLon(51.127, 1.338); * var p2 = new LatLon(50.964, 1.853); * var d = p1.distanceTo(p2); // 40.31 km */ function calculateRhumbDistance(origin, destination, radius) { // φ => phi // λ => lambda // ψ => psi // Δ => Delta // δ => delta // θ => theta radius = (radius === undefined) ? rhumb_distance_node_modules_turf_helpers_main_es_earthRadius : Number(radius); // see www.edwilliams.org/avform.htm#Rhumb var R = radius; var phi1 = origin[1] * Math.PI / 180; var phi2 = destination[1] * Math.PI / 180; var DeltaPhi = phi2 - phi1; var DeltaLambda = Math.abs(destination[0] - origin[0]) * Math.PI / 180; // if dLon over 180° take shorter rhumb line across the anti-meridian: if (DeltaLambda > Math.PI) DeltaLambda -= 2 * Math.PI; // on Mercator projection, longitude distances shrink by latitude; q is the 'stretch factor' // q becomes ill-conditioned along E-W line (0/0); use empirical tolerance to avoid it var DeltaPsi = Math.log(Math.tan(phi2 / 2 + Math.PI / 4) / Math.tan(phi1 / 2 + Math.PI / 4)); var q = Math.abs(DeltaPsi) > 10e-12 ? DeltaPhi / DeltaPsi : Math.cos(phi1); // distance is pythagoras on 'stretched' Mercator projection var delta = Math.sqrt(DeltaPhi * DeltaPhi + q * q * DeltaLambda * DeltaLambda); // angular distance in radians var dist = delta * R; return dist; } /* harmony default export */ var rhumb_distance_main_es = (rhumbDistance); ;// CONCATENATED MODULE: ./node_modules/@turf/rhumb-destination/node_modules/@turf/helpers/main.es.js /** * Earth Radius used with the Harvesine formula and approximates using a spherical (non-ellipsoid) Earth. */ var rhumb_destination_node_modules_turf_helpers_main_es_earthRadius = 6371008.8; /** * Unit of measurement factors using a spherical (non-ellipsoid) earth radius. */ var rhumb_destination_node_modules_turf_helpers_main_es_factors = { meters: rhumb_destination_node_modules_turf_helpers_main_es_earthRadius, metres: rhumb_destination_node_modules_turf_helpers_main_es_earthRadius, millimeters: rhumb_destination_node_modules_turf_helpers_main_es_earthRadius * 1000, millimetres: rhumb_destination_node_modules_turf_helpers_main_es_earthRadius * 1000, centimeters: rhumb_destination_node_modules_turf_helpers_main_es_earthRadius * 100, centimetres: rhumb_destination_node_modules_turf_helpers_main_es_earthRadius * 100, kilometers: rhumb_destination_node_modules_turf_helpers_main_es_earthRadius / 1000, kilometres: rhumb_destination_node_modules_turf_helpers_main_es_earthRadius / 1000, miles: rhumb_destination_node_modules_turf_helpers_main_es_earthRadius / 1609.344, nauticalmiles: rhumb_destination_node_modules_turf_helpers_main_es_earthRadius / 1852, inches: rhumb_destination_node_modules_turf_helpers_main_es_earthRadius * 39.370, yards: rhumb_destination_node_modules_turf_helpers_main_es_earthRadius / 1.0936, feet: rhumb_destination_node_modules_turf_helpers_main_es_earthRadius * 3.28084, radians: 1, degrees: rhumb_destination_node_modules_turf_helpers_main_es_earthRadius / 111325, }; /** * Units of measurement factors based on 1 meter. */ var rhumb_destination_node_modules_turf_helpers_main_es_unitsFactors = { meters: 1, metres: 1, millimeters: 1000, millimetres: 1000, centimeters: 100, centimetres: 100, kilometers: 1 / 1000, kilometres: 1 / 1000, miles: 1 / 1609.344, nauticalmiles: 1 / 1852, inches: 39.370, yards: 1 / 1.0936, feet: 3.28084, radians: 1 / rhumb_destination_node_modules_turf_helpers_main_es_earthRadius, degrees: 1 / 111325, }; /** * Area of measurement factors based on 1 square meter. */ var rhumb_destination_node_modules_turf_helpers_main_es_areaFactors = { meters: 1, metres: 1, millimeters: 1000000, millimetres: 1000000, centimeters: 10000, centimetres: 10000, kilometers: 0.000001, kilometres: 0.000001, acres: 0.000247105, miles: 3.86e-7, yards: 1.195990046, feet: 10.763910417, inches: 1550.003100006 }; /** * 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} [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 rhumb_destination_node_modules_turf_helpers_main_es_feature(geometry, properties, options) { // Optional Parameters options = options || {}; if (!rhumb_destination_node_modules_turf_helpers_main_es_isObject(options)) throw new Error('options is invalid'); var bbox = options.bbox; var id = options.id; // Validation if (geometry === undefined) throw new Error('geometry is required'); if (properties && properties.constructor !== Object) throw new Error('properties must be an Object'); if (bbox) rhumb_destination_node_modules_turf_helpers_main_es_validateBBox(bbox); if (id) rhumb_destination_node_modules_turf_helpers_main_es_validateId(id); // Main var feat = {type: 'Feature'}; if (id) feat.id = id; if (bbox) feat.bbox = bbox; feat.properties = properties || {}; feat.geometry = geometry; return feat; } /** * 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} coordinates Coordinates * @param {Object} [options={}] Optional Parameters * @param {Array} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Geometry * @returns {Geometry} a GeoJSON Geometry * @example * var type = 'Point'; * var coordinates = [110, 50]; * * var geometry = turf.geometry(type, coordinates); * * //=geometry */ function rhumb_destination_node_modules_turf_helpers_main_es_geometry(type, coordinates, options) { // Optional Parameters options = options || {}; if (!rhumb_destination_node_modules_turf_helpers_main_es_isObject(options)) throw new Error('options is invalid'); var bbox = options.bbox; // Validation if (!type) throw new Error('type is required'); if (!coordinates) throw new Error('coordinates is required'); if (!Array.isArray(coordinates)) throw new Error('coordinates must be an Array'); if (bbox) rhumb_destination_node_modules_turf_helpers_main_es_validateBBox(bbox); // Main var geom; switch (type) { case 'Point': geom = rhumb_destination_node_modules_turf_helpers_main_es_point(coordinates).geometry; break; case 'LineString': geom = rhumb_destination_node_modules_turf_helpers_main_es_lineString(coordinates).geometry; break; case 'Polygon': geom = rhumb_destination_node_modules_turf_helpers_main_es_polygon(coordinates).geometry; break; case 'MultiPoint': geom = rhumb_destination_node_modules_turf_helpers_main_es_multiPoint(coordinates).geometry; break; case 'MultiLineString': geom = rhumb_destination_node_modules_turf_helpers_main_es_multiLineString(coordinates).geometry; break; case 'MultiPolygon': geom = rhumb_destination_node_modules_turf_helpers_main_es_multiPolygon(coordinates).geometry; break; default: throw new Error(type + ' is invalid'); } if (bbox) geom.bbox = bbox; return geom; } /** * Creates a {@link Point} {@link Feature} from a Position. * * @name point * @param {Array} 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} [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 Point feature * @example * var point = turf.point([-75.343, 39.984]); * * //=point */ function rhumb_destination_node_modules_turf_helpers_main_es_point(coordinates, properties, options) { if (!coordinates) throw new Error('coordinates is required'); if (!Array.isArray(coordinates)) throw new Error('coordinates must be an Array'); if (coordinates.length < 2) throw new Error('coordinates must be at least 2 numbers long'); if (!rhumb_destination_node_modules_turf_helpers_main_es_isNumber(coordinates[0]) || !rhumb_destination_node_modules_turf_helpers_main_es_isNumber(coordinates[1])) throw new Error('coordinates must contain numbers'); return rhumb_destination_node_modules_turf_helpers_main_es_feature({ type: 'Point', coordinates: coordinates }, properties, options); } /** * Creates a {@link Point} {@link FeatureCollection} from an Array of Point coordinates. * * @name points * @param {Array>} coordinates an array of Points * @param {Object} [properties={}] Translate these properties to each Feature * @param {Object} [options={}] Optional Parameters * @param {Array} [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 Feature * @example * var points = turf.points([ * [-75, 39], * [-80, 45], * [-78, 50] * ]); * * //=points */ function rhumb_destination_node_modules_turf_helpers_main_es_points(coordinates, properties, options) { if (!coordinates) throw new Error('coordinates is required'); if (!Array.isArray(coordinates)) throw new Error('coordinates must be an Array'); return rhumb_destination_node_modules_turf_helpers_main_es_featureCollection(coordinates.map(function (coords) { return rhumb_destination_node_modules_turf_helpers_main_es_point(coords, properties); }), options); } /** * Creates a {@link Polygon} {@link Feature} from an Array of LinearRings. * * @name polygon * @param {Array>>} 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} [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 Feature * @example * var polygon = turf.polygon([[[-5, 52], [-4, 56], [-2, 51], [-7, 54], [-5, 52]]], { name: 'poly1' }); * * //=polygon */ function rhumb_destination_node_modules_turf_helpers_main_es_polygon(coordinates, properties, options) { if (!coordinates) throw new Error('coordinates is required'); for (var i = 0; i < coordinates.length; i++) { var ring = coordinates[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 (i === 0 && j === 0 && !rhumb_destination_node_modules_turf_helpers_main_es_isNumber(ring[0][0]) || !rhumb_destination_node_modules_turf_helpers_main_es_isNumber(ring[0][1])) throw new Error('coordinates must contain numbers'); if (ring[ring.length - 1][j] !== ring[0][j]) { throw new Error('First and last Position are not equivalent.'); } } } return rhumb_destination_node_modules_turf_helpers_main_es_feature({ type: 'Polygon', coordinates: coordinates }, properties, options); } /** * Creates a {@link Polygon} {@link FeatureCollection} from an Array of Polygon coordinates. * * @name polygons * @param {Array>>>} 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} [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 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 rhumb_destination_node_modules_turf_helpers_main_es_polygons(coordinates, properties, options) { if (!coordinates) throw new Error('coordinates is required'); if (!Array.isArray(coordinates)) throw new Error('coordinates must be an Array'); return rhumb_destination_node_modules_turf_helpers_main_es_featureCollection(coordinates.map(function (coords) { return rhumb_destination_node_modules_turf_helpers_main_es_polygon(coords, properties); }), options); } /** * Creates a {@link LineString} {@link Feature} from an Array of Positions. * * @name lineString * @param {Array>} 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} [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 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 rhumb_destination_node_modules_turf_helpers_main_es_lineString(coordinates, properties, options) { if (!coordinates) throw new Error('coordinates is required'); if (coordinates.length < 2) throw new Error('coordinates must be an array of two or more positions'); // Check if first point of LineString contains two numbers if (!rhumb_destination_node_modules_turf_helpers_main_es_isNumber(coordinates[0][1]) || !rhumb_destination_node_modules_turf_helpers_main_es_isNumber(coordinates[0][1])) throw new Error('coordinates must contain numbers'); return rhumb_destination_node_modules_turf_helpers_main_es_feature({ type: 'LineString', coordinates: coordinates }, properties, options); } /** * Creates a {@link LineString} {@link FeatureCollection} from an Array of LineString coordinates. * * @name lineStrings * @param {Array>} 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} [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 FeatureCollection * @example * var linestrings = turf.lineStrings([ * [[-24, 63], [-23, 60], [-25, 65], [-20, 69]], * [[-14, 43], [-13, 40], [-15, 45], [-10, 49]] * ]); * * //=linestrings */ function rhumb_destination_node_modules_turf_helpers_main_es_lineStrings(coordinates, properties, options) { if (!coordinates) throw new Error('coordinates is required'); if (!Array.isArray(coordinates)) throw new Error('coordinates must be an Array'); return rhumb_destination_node_modules_turf_helpers_main_es_featureCollection(coordinates.map(function (coords) { return rhumb_destination_node_modules_turf_helpers_main_es_lineString(coords, properties); }), options); } /** * 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} [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 rhumb_destination_node_modules_turf_helpers_main_es_featureCollection(features, options) { // Optional Parameters options = options || {}; if (!rhumb_destination_node_modules_turf_helpers_main_es_isObject(options)) throw new Error('options is invalid'); var bbox = options.bbox; var id = options.id; // Validation if (!features) throw new Error('No features passed'); if (!Array.isArray(features)) throw new Error('features must be an Array'); if (bbox) rhumb_destination_node_modules_turf_helpers_main_es_validateBBox(bbox); if (id) rhumb_destination_node_modules_turf_helpers_main_es_validateId(id); // Main var fc = {type: 'FeatureCollection'}; if (id) fc.id = id; if (bbox) fc.bbox = bbox; fc.features = features; return fc; } /** * Creates a {@link Feature} based on a * coordinate array. Properties can be added optionally. * * @name multiLineString * @param {Array>>} 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} [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 MultiLineString feature * @throws {Error} if no coordinates are passed * @example * var multiLine = turf.multiLineString([[[0,0],[10,10]]]); * * //=multiLine */ function rhumb_destination_node_modules_turf_helpers_main_es_multiLineString(coordinates, properties, options) { if (!coordinates) throw new Error('coordinates is required'); return rhumb_destination_node_modules_turf_helpers_main_es_feature({ type: 'MultiLineString', coordinates: coordinates }, properties, options); } /** * Creates a {@link Feature} based on a * coordinate array. Properties can be added optionally. * * @name multiPoint * @param {Array>} 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} [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 MultiPoint feature * @throws {Error} if no coordinates are passed * @example * var multiPt = turf.multiPoint([[0,0],[10,10]]); * * //=multiPt */ function rhumb_destination_node_modules_turf_helpers_main_es_multiPoint(coordinates, properties, options) { if (!coordinates) throw new Error('coordinates is required'); return rhumb_destination_node_modules_turf_helpers_main_es_feature({ type: 'MultiPoint', coordinates: coordinates }, properties, options); } /** * Creates a {@link Feature} based on a * coordinate array. Properties can be added optionally. * * @name multiPolygon * @param {Array>>>} 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} [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 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 rhumb_destination_node_modules_turf_helpers_main_es_multiPolygon(coordinates, properties, options) { if (!coordinates) throw new Error('coordinates is required'); return rhumb_destination_node_modules_turf_helpers_main_es_feature({ type: 'MultiPolygon', coordinates: coordinates }, properties, options); } /** * Creates a {@link Feature} based on a * coordinate array. Properties can be added optionally. * * @name geometryCollection * @param {Array} 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} [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 GeometryCollection Feature * @example * var pt = { * "type": "Point", * "coordinates": [100, 0] * }; * var line = { * "type": "LineString", * "coordinates": [ [101, 0], [102, 1] ] * }; * var collection = turf.geometryCollection([pt, line]); * * //=collection */ function rhumb_destination_node_modules_turf_helpers_main_es_geometryCollection(geometries, properties, options) { if (!geometries) throw new Error('geometries is required'); if (!Array.isArray(geometries)) throw new Error('geometries must be an Array'); return rhumb_destination_node_modules_turf_helpers_main_es_feature({ type: 'GeometryCollection', geometries: geometries }, properties, options); } /** * 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 rhumb_destination_node_modules_turf_helpers_main_es_round(num, precision) { if (num === undefined || num === null || isNaN(num)) throw new Error('num is required'); 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; } /** * 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 rhumb_destination_node_modules_turf_helpers_main_es_radiansToLength(radians, units) { if (radians === undefined || radians === null) throw new Error('radians is required'); if (units && typeof units !== 'string') throw new Error('units must be a string'); var factor = rhumb_destination_node_modules_turf_helpers_main_es_factors[units || 'kilometers']; if (!factor) throw new Error(units + ' units is invalid'); return radians * factor; } /** * 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 rhumb_destination_node_modules_turf_helpers_main_es_lengthToRadians(distance, units) { if (distance === undefined || distance === null) throw new Error('distance is required'); if (units && typeof units !== 'string') throw new Error('units must be a string'); var factor = rhumb_destination_node_modules_turf_helpers_main_es_factors[units || 'kilometers']; if (!factor) throw new Error(units + ' units is invalid'); return distance / factor; } /** * 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 rhumb_destination_node_modules_turf_helpers_main_es_lengthToDegrees(distance, units) { return rhumb_destination_node_modules_turf_helpers_main_es_radiansToDegrees(rhumb_destination_node_modules_turf_helpers_main_es_lengthToRadians(distance, units)); } /** * 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 rhumb_destination_node_modules_turf_helpers_main_es_bearingToAzimuth(bearing) { if (bearing === null || bearing === undefined) throw new Error('bearing is required'); var angle = bearing % 360; if (angle < 0) angle += 360; return angle; } /** * Converts an angle in radians to degrees * * @name radiansToDegrees * @param {number} radians angle in radians * @returns {number} degrees between 0 and 360 degrees */ function rhumb_destination_node_modules_turf_helpers_main_es_radiansToDegrees(radians) { if (radians === null || radians === undefined) throw new Error('radians is required'); var degrees = radians % (2 * Math.PI); return degrees * 180 / Math.PI; } /** * Converts an angle in degrees to radians * * @name degreesToRadians * @param {number} degrees angle between 0 and 360 degrees * @returns {number} angle in radians */ function rhumb_destination_node_modules_turf_helpers_main_es_degreesToRadians(degrees) { if (degrees === null || degrees === undefined) throw new Error('degrees is required'); var radians = degrees % 360; return radians * Math.PI / 180; } /** * 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 {string} originalUnit of the length * @param {string} [finalUnit='kilometers'] returned unit * @returns {number} the converted length */ function rhumb_destination_node_modules_turf_helpers_main_es_convertLength(length, originalUnit, finalUnit) { if (length === null || length === undefined) throw new Error('length is required'); if (!(length >= 0)) throw new Error('length must be a positive number'); return rhumb_destination_node_modules_turf_helpers_main_es_radiansToLength(rhumb_destination_node_modules_turf_helpers_main_es_lengthToRadians(length, originalUnit), finalUnit || 'kilometers'); } /** * 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 {string} [originalUnit='meters'] of the distance * @param {string} [finalUnit='kilometers'] returned unit * @returns {number} the converted distance */ function rhumb_destination_node_modules_turf_helpers_main_es_convertArea(area, originalUnit, finalUnit) { if (area === null || area === undefined) throw new Error('area is required'); if (!(area >= 0)) throw new Error('area must be a positive number'); var startFactor = rhumb_destination_node_modules_turf_helpers_main_es_areaFactors[originalUnit || 'meters']; if (!startFactor) throw new Error('invalid original units'); var finalFactor = rhumb_destination_node_modules_turf_helpers_main_es_areaFactors[finalUnit || 'kilometers']; if (!finalFactor) throw new Error('invalid final units'); return (area / startFactor) * finalFactor; } /** * isNumber * * @param {*} num Number to validate * @returns {boolean} true/false * @example * turf.isNumber(123) * //=true * turf.isNumber('foo') * //=false */ function rhumb_destination_node_modules_turf_helpers_main_es_isNumber(num) { return !isNaN(num) && num !== null && !Array.isArray(num); } /** * isObject * * @param {*} input variable to validate * @returns {boolean} true/false * @example * turf.isObject({elevation: 10}) * //=true * turf.isObject('foo') * //=false */ function rhumb_destination_node_modules_turf_helpers_main_es_isObject(input) { return (!!input) && (input.constructor === Object); } /** * Validate BBox * * @private * @param {Array} 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 rhumb_destination_node_modules_turf_helpers_main_es_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 (!rhumb_destination_node_modules_turf_helpers_main_es_isNumber(num)) throw new Error('bbox must only contain numbers'); }); } /** * 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 rhumb_destination_node_modules_turf_helpers_main_es_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'); } // Deprecated methods function rhumb_destination_node_modules_turf_helpers_main_es_radians2degrees() { throw new Error('method has been renamed to `radiansToDegrees`'); } function rhumb_destination_node_modules_turf_helpers_main_es_degrees2radians() { throw new Error('method has been renamed to `degreesToRadians`'); } function rhumb_destination_node_modules_turf_helpers_main_es_distanceToDegrees() { throw new Error('method has been renamed to `lengthToDegrees`'); } function rhumb_destination_node_modules_turf_helpers_main_es_distanceToRadians() { throw new Error('method has been renamed to `lengthToRadians`'); } function rhumb_destination_node_modules_turf_helpers_main_es_radiansToDistance() { throw new Error('method has been renamed to `radiansToLength`'); } function rhumb_destination_node_modules_turf_helpers_main_es_bearingToAngle() { throw new Error('method has been renamed to `bearingToAzimuth`'); } function rhumb_destination_node_modules_turf_helpers_main_es_convertDistance() { throw new Error('method has been renamed to `convertLength`'); } ;// CONCATENATED MODULE: ./node_modules/@turf/rhumb-destination/main.es.js // https://en.wikipedia.org/wiki/Rhumb_line /** * Returns the destination {@link Point} having travelled the given distance along a Rhumb line from the * origin Point with the (varant) given bearing. * * @name rhumbDestination * @param {Coord} origin starting point * @param {number} distance distance from the starting point * @param {number} bearing varant bearing angle ranging from -180 to 180 degrees from north * @param {Object} [options={}] Optional parameters * @param {string} [options.units='kilometers'] can be degrees, radians, miles, or kilometers * @param {Object} [options.properties={}] translate properties to destination point * @returns {Feature} Destination point. * @example * var pt = turf.point([-75.343, 39.984], {"marker-color": "F00"}); * var distance = 50; * var bearing = 90; * var options = {units: 'miles'}; * * var destination = turf.rhumbDestination(pt, distance, bearing, options); * * //addToMap * var addToMap = [pt, destination] * destination.properties['marker-color'] = '#00F'; */ function rhumbDestination(origin, distance, bearing, options) { // Optional parameters options = options || {}; if (!rhumb_destination_node_modules_turf_helpers_main_es_isObject(options)) throw new Error('options is invalid'); var units = options.units; var properties = options.properties; // validation if (!origin) throw new Error('origin is required'); if (distance === undefined || distance === null) throw new Error('distance is required'); if (bearing === undefined || bearing === null) throw new Error('bearing is required'); if (!(distance >= 0)) throw new Error('distance must be greater than 0'); var distanceInMeters = rhumb_destination_node_modules_turf_helpers_main_es_convertLength(distance, units, 'meters'); var coords = getCoord(origin); var destination = calculateRhumbDestination(coords, distanceInMeters, bearing); // compensate the crossing of the 180th meridian (https://macwright.org/2016/09/26/the-180th-meridian.html) // solution from https://github.com/mapbox/mapbox-gl-js/issues/3250#issuecomment-294887678 destination[0] += (destination[0] - coords[0] > 180) ? -360 : (coords[0] - destination[0] > 180) ? 360 : 0; return rhumb_destination_node_modules_turf_helpers_main_es_point(destination, properties); } /** * Returns the destination point having travelled along a rhumb line from origin point the given * distance on the given bearing. * Adapted from Geodesy: http://www.movable-type.co.uk/scripts/latlong.html#rhumblines * * @private * @param {Array} origin - point * @param {number} distance - Distance travelled, in same units as earth radius (default: metres). * @param {number} bearing - Bearing in degrees from north. * @param {number} [radius=6371e3] - (Mean) radius of earth (defaults to radius in metres). * @returns {Array} Destination point. */ function calculateRhumbDestination(origin, distance, bearing, radius) { // φ => phi // λ => lambda // ψ => psi // Δ => Delta // δ => delta // θ => theta radius = (radius === undefined) ? rhumb_destination_node_modules_turf_helpers_main_es_earthRadius : Number(radius); var delta = distance / radius; // angular distance in radians var lambda1 = origin[0] * Math.PI / 180; // to radians, but without normalize to 𝜋 var phi1 = rhumb_destination_node_modules_turf_helpers_main_es_degreesToRadians(origin[1]); var theta = rhumb_destination_node_modules_turf_helpers_main_es_degreesToRadians(bearing); var DeltaPhi = delta * Math.cos(theta); var phi2 = phi1 + DeltaPhi; // check for some daft bugger going past the pole, normalise latitude if so if (Math.abs(phi2) > Math.PI / 2) phi2 = phi2 > 0 ? Math.PI - phi2 : -Math.PI - phi2; var DeltaPsi = Math.log(Math.tan(phi2 / 2 + Math.PI / 4) / Math.tan(phi1 / 2 + Math.PI / 4)); var q = Math.abs(DeltaPsi) > 10e-12 ? DeltaPhi / DeltaPsi : Math.cos(phi1); // E-W course becomes ill-conditioned with 0/0 var DeltaLambda = delta * Math.sin(theta) / q; var lambda2 = lambda1 + DeltaLambda; return [((lambda2 * 180 / Math.PI) + 540) % 360 - 180, phi2 * 180 / Math.PI]; // normalise to −180..+180° } /* harmony default export */ var rhumb_destination_main_es = (rhumbDestination); ;// CONCATENATED MODULE: ./node_modules/@turf/transform-scale/main.es.js /** * Scale a GeoJSON from a given point by a factor of scaling (ex: factor=2 would make the GeoJSON 200% larger). * If a FeatureCollection is provided, the origin point will be calculated based on each individual Feature. * * @name transformScale * @param {GeoJSON} geojson GeoJSON to be scaled * @param {number} factor of scaling, positive or negative values greater than 0 * @param {Object} [options={}] Optional parameters * @param {string|Coord} [options.origin='centroid'] Point from which the scaling will occur (string options: sw/se/nw/ne/center/centroid) * @param {boolean} [options.mutate=false] allows GeoJSON input to be mutated (significant performance increase if true) * @returns {GeoJSON} scaled GeoJSON * @example * var poly = turf.polygon([[[0,29],[3.5,29],[2.5,32],[0,29]]]); * var scaledPoly = turf.transformScale(poly, 3); * * //addToMap * var addToMap = [poly, scaledPoly]; * scaledPoly.properties = {stroke: '#F00', 'stroke-width': 4}; */ function transformScale(geojson, factor, options) { // Optional parameters options = options || {}; if (!_turf_helpers_main_es_isObject(options)) throw new Error('options is invalid'); var origin = options.origin; var mutate = options.mutate; // Input validation if (!geojson) throw new Error('geojson required'); if (typeof factor !== 'number' || factor === 0) throw new Error('invalid factor'); var originIsPoint = Array.isArray(origin) || typeof origin === 'object'; // Clone geojson to avoid side effects if (mutate !== true) geojson = main_es(geojson); // Scale each Feature separately if (geojson.type === 'FeatureCollection' && !originIsPoint) { meta_main_es_featureEach(geojson, function (feature, index) { geojson.features[index] = scale(feature, factor, origin); }); return geojson; } // Scale Feature/Geometry return scale(geojson, factor, origin); } /** * Scale Feature/Geometry * * @private * @param {Feature|Geometry} feature GeoJSON Feature/Geometry * @param {number} factor of scaling, positive or negative values greater than 0 * @param {string|Coord} [origin="centroid"] Point from which the scaling will occur (string options: sw/se/nw/ne/center/centroid) * @returns {Feature|Geometry} scaled GeoJSON Feature/Geometry */ function scale(feature, factor, origin) { // Default params var isPoint = getType(feature) === 'Point'; origin = defineOrigin(feature, origin); // Shortcut no-scaling if (factor === 1 || isPoint) return feature; // Scale each coordinate meta_main_es_coordEach(feature, function (coord) { var originalDistance = rhumb_distance_main_es(origin, coord); var bearing = rhumb_bearing_main_es(origin, coord); var newDistance = originalDistance * factor; var newCoord = getCoords(rhumb_destination_main_es(origin, newDistance, bearing)); coord[0] = newCoord[0]; coord[1] = newCoord[1]; if (coord.length === 3) coord[2] *= factor; }); return feature; } /** * Define Origin * * @private * @param {GeoJSON} geojson GeoJSON * @param {string|Coord} origin sw/se/nw/ne/center/centroid * @returns {Feature} Point origin */ function defineOrigin(geojson, origin) { // Default params if (origin === undefined || origin === null) origin = 'centroid'; // Input Coord if (Array.isArray(origin) || typeof origin === 'object') return getCoord(origin); // Define BBox var bbox = (geojson.bbox) ? geojson.bbox : _turf_bbox_main_es(geojson); var west = bbox[0]; var south = bbox[1]; var east = bbox[2]; var north = bbox[3]; switch (origin) { case 'sw': case 'southwest': case 'westsouth': case 'bottomleft': return _turf_helpers_main_es_point([west, south]); case 'se': case 'southeast': case 'eastsouth': case 'bottomright': return _turf_helpers_main_es_point([east, south]); case 'nw': case 'northwest': case 'westnorth': case 'topleft': return _turf_helpers_main_es_point([west, north]); case 'ne': case 'northeast': case 'eastnorth': case 'topright': return _turf_helpers_main_es_point([east, north]); case 'center': return center_main_es(geojson); case undefined: case null: case 'centroid': return centroid_main_es(geojson); default: throw new Error('invalid origin'); } } /* harmony default export */ var transform_scale_main_es = (transformScale); /***/ }), /***/ 9458: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; var _interopRequireDefault=(__webpack_require__(4836)["default"]);var _slicedToArray2=_interopRequireDefault(__webpack_require__(885));/*jshint esversion: 6 */function colorcolor(color){var newColor=arguments.length>1&&arguments[1]!==undefined?arguments[1]:"rgba";var calculateOpacity=arguments.length>2&&arguments[2]!==undefined?arguments[2]:false;color=color.toLowerCase();newColor=newColor.toLowerCase();var returnedColor=color;var namedColor=__webpack_require__(8874);var r,g,b,a;var roundTo=4;var colorDefinitions={rgb:{re:/^rgb\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3})\)$/,example:["rgb(123, 234, 45)","rgb(255,234,245)"],toRGBA:function toRGBA(bits){return[parseInt(bits[1],10),parseInt(bits[2],10),parseInt(bits[3],10),1];}},rgba:{re:/^rgba\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3}),\s*(\d+(?:\.\d+)?|\.\d+)\s*\)/,example:["rgba(123, 234, 45, 1)","rgba(255,234,245, 0.5)"],toRGBA:function toRGBA(bits){return[parseInt(bits[1],10),parseInt(bits[2],10),parseInt(bits[3],10),parseFloat(bits[4])];}},hex:{re:/^#([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/,example:["00ff00","336699"],toRGBA:function toRGBA(bits){return[parseInt(bits[1],16),parseInt(bits[2],16),parseInt(bits[3],16),1];}},hex3:{re:/^#([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,example:["fb0","f0f"],toRGBA:function toRGBA(bits){return[parseInt(bits[1]+bits[1],16),parseInt(bits[2]+bits[2],16),parseInt(bits[3]+bits[3],16),1];}},hexa:{re:/^#([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/,example:["00ff00ff","336699a0"],toRGBA:function toRGBA(bits){return[parseInt(bits[1],16),parseInt(bits[2],16),parseInt(bits[3],16),parseInt(bits[4],16)/255];}},hex4a:{re:/^#([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,example:["fb0f","f0f8"],toRGBA:function toRGBA(bits){return[parseInt(bits[1]+bits[1],16),parseInt(bits[2]+bits[2],16),parseInt(bits[3]+bits[3],16),parseInt(bits[4]+bits[4],16)/255];}},hsl:{re:/^hsl\((\d{1,3}),\s*(\d{1,3})%,\s*(\d{1,3})%\)$/,example:["hsl(120, 100%, 25%)","hsl(0, 100%, 50%)"],toRGBA:function toRGBA(bits){bits[4]=1;var rgba=hslToRgb(bits);return[rgba.r,rgba.g,rgba.b,rgba.a];}},hsla:{re:/^hsla\((\d{1,3}),\s*(\d{1,3})%,\s*(\d{1,3})%,\s*(\d+(?:\.\d+)?|\.\d+)\s*\)/,example:["hsla(120, 100%, 25%, 1)","hsla(0, 100%, 50%, 0.5)"],toRGBA:function toRGBA(bits){var rgba=hslToRgb(bits);return[rgba.r,rgba.g,rgba.b,rgba.a];}},hsv:{re:/^hsv\((\d{1,3}),\s*(\d{1,3})%,\s*(\d{1,3})%\)$/,example:["hsv(120, 100%, 25%)","hsv(0, 100%, 50%)"],toRGBA:function toRGBA(bits){var rgb=hsvToRgb(bits);return[rgb.r,rgb.g,rgb.b,1];}},hsb:{re:/^hsb\((\d{1,3}),\s*(\d{1,3})%,\s*(\d{1,3})%\)$/,example:["hsb(120, 100%, 25%)","hsb(0, 100%, 50%)"],toRGBA:function toRGBA(bits){var rgb=hsvToRgb(bits);return[rgb.r,rgb.g,rgb.b,1];}}};// If this is a named color, convert it to hex if(namedColor.hasOwnProperty(color)){color=namedColor[color];color.forEach(function(piece,index){"use strict";color[index]=("0"+piece.toString(16)).slice(-2);});color="#"+color.join('');}// Search the color definitions for a match for(var colorDefinition in colorDefinitions){var re=colorDefinitions[colorDefinition].re;var processor=colorDefinitions[colorDefinition].toRGBA;var bits=re.exec(color);if(bits){var channels=processor(bits);r=channels[0];g=channels[1];b=channels[2];a=+(Math.round(channels[3]+("e+"+roundTo))+("e-"+roundTo));}}r=Math.round(r<0||isNaN(r)?0:r>255?255:r);g=Math.round(g<0||isNaN(g)?0:g>255?255:g);b=Math.round(b<0||isNaN(b)?0:b>255?255:b);a=a<0||isNaN(a)?0:a>1?1:a;switch(newColor){case"hex":returnedColor="#"+("0"+r.toString(16)).slice(-2)+("0"+g.toString(16)).slice(-2)+("0"+b.toString(16)).slice(-2);break;case"hexa":if(calculateOpacity){var _calculateOpacityFrom=calculateOpacityFromWhite(r,g,b,a);var _calculateOpacityFrom2=(0,_slicedToArray2.default)(_calculateOpacityFrom,4);r=_calculateOpacityFrom2[0];g=_calculateOpacityFrom2[1];b=_calculateOpacityFrom2[2];a=_calculateOpacityFrom2[3];}returnedColor="#"+("0"+r.toString(16)).slice(-2)+("0"+g.toString(16)).slice(-2)+("0"+b.toString(16)).slice(-2)+("0"+Math.round(255*a).toString(16)).slice(-2);break;case"hsl":var hsl=rgbToHsl({"r":r,"g":g,"b":b});returnedColor="hsl(".concat(hsl.h,",").concat(hsl.s,"%,").concat(hsl.l,"%)");break;case"hsla":if(calculateOpacity){var _calculateOpacityFrom3=calculateOpacityFromWhite(r,g,b,a);var _calculateOpacityFrom4=(0,_slicedToArray2.default)(_calculateOpacityFrom3,4);r=_calculateOpacityFrom4[0];g=_calculateOpacityFrom4[1];b=_calculateOpacityFrom4[2];a=_calculateOpacityFrom4[3];}var hsla=rgbToHsl({"r":r,"g":g,"b":b,"a":a});returnedColor="hsla(".concat(hsla.h,",").concat(hsla.s,"%,").concat(hsla.l,"%,").concat(hsla.a,")");break;case"hsb":/* Same as `hsv` */var hsb=rgbToHsv({"r":r,"g":g,"b":b});returnedColor="hsb(".concat(hsb.h,",").concat(hsb.s,"%,").concat(hsb.v,"%)");break;case"hsv":var hsv=rgbToHsv({"r":r,"g":g,"b":b});returnedColor="hsv(".concat(hsv.h,",").concat(hsv.s,"%,").concat(hsv.v,"%)");break;case"rgb":returnedColor="rgb(".concat(r,",").concat(g,",").concat(b,")");break;case"rgba":/* falls through */default:if(calculateOpacity){var _calculateOpacityFrom5=calculateOpacityFromWhite(r,g,b,a);var _calculateOpacityFrom6=(0,_slicedToArray2.default)(_calculateOpacityFrom5,4);r=_calculateOpacityFrom6[0];g=_calculateOpacityFrom6[1];b=_calculateOpacityFrom6[2];a=_calculateOpacityFrom6[3];}returnedColor="rgba(".concat(r,",").concat(g,",").concat(b,",").concat(a,")");break;}return returnedColor;}function calculateOpacityFromWhite(r,g,b,a){"use strict";var min=0;a=(255-(min=Math.min(r,g,b)))/255;r=( false||(r-min)/a).toFixed(0);g=( false||(g-min)/a).toFixed(0);b=( false||(b-min)/a).toFixed(0);a=parseFloat(a.toFixed(4));return[r,g,b,a];}function hslToRgb(bits){var rgba={},hsl={h:bits[1]/360,s:bits[2]/100,l:bits[3]/100,a:parseFloat(bits[4])};if(hsl.s===0){var v=255*hsl.l;rgba={r:v,g:v,b:v,a:hsl.a};}else{var q=hsl.l<0.5?hsl.l*(1+hsl.s):hsl.l+hsl.s-hsl.l*hsl.s;var p=2*hsl.l-q;rgba.r=hueToRgb(p,q,hsl.h+1/3)*255;rgba.g=hueToRgb(p,q,hsl.h)*255;rgba.b=hueToRgb(p,q,hsl.h-1/3)*255;rgba.a=hsl.a;}return rgba;}function rgbToHsl(rgba){rgba.r=rgba.r/255;rgba.g=rgba.g/255;rgba.b=rgba.b/255;var max=Math.max(rgba.r,rgba.g,rgba.b),min=Math.min(rgba.r,rgba.g,rgba.b),hsl=[],d;hsl.a=rgba.a;hsl.l=(max+min)/2;if(max===min){hsl.h=0;hsl.s=0;}else{d=max-min;hsl.s=hsl.l>=0.5?d/(2-max-min):d/(max+min);switch(max){case rgba.r:hsl.h=(rgba.g-rgba.b)/d+(rgba.g1){t-=1;}if(t<1/6){return p+(q-p)*6*t;}if(t<1/2){return q;}if(t<2/3){return p+(q-p)*((2/3-t)*6);}return p;}function toPercent(amount,limit){return amount/limit;}module.exports=colorcolor;__webpack_require__.g.colorcolor=module.exports;/* ew */ /***/ }), /***/ 1892: /***/ (function(__unused_webpack_module, exports) { "use strict"; Object.defineProperty(exports, "__esModule", ({value:true}));exports.addListener=addListener;exports.removeListener=removeListener;var raf=null;function requestAnimationFrame(callback){if(!raf){raf=(window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||function(callback){return setTimeout(callback,16);}).bind(window);}return raf(callback);}var caf=null;function cancelAnimationFrame(id){if(!caf){caf=(window.cancelAnimationFrame||window.webkitCancelAnimationFrame||window.mozCancelAnimationFrame||function(id){clearTimeout(id);}).bind(window);}caf(id);}function createStyles(styleText){var style=document.createElement('style');style.type='text/css';if(style.styleSheet){style.styleSheet.cssText=styleText;}else{style.appendChild(document.createTextNode(styleText));}(document.querySelector('head')||document.body).appendChild(style);return style;}function createElement(tagName){var props=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};var elem=document.createElement(tagName);Object.keys(props).forEach(function(key){elem[key]=props[key];});return elem;}function getComputedStyle(elem,prop,pseudo){// for older versions of Firefox, `getComputedStyle` required // the second argument and may return `null` for some elements // when `display: none` var computedStyle=window.getComputedStyle(elem,pseudo||null)||{display:'none'};return computedStyle[prop];}function getRenderInfo(elem){if(!document.documentElement.contains(elem)){return{detached:true,rendered:false};}var current=elem;while(current!==document){if(getComputedStyle(current,'display')==='none'){return{detached:false,rendered:false};}current=current.parentNode;}return{detached:false,rendered:true};}var css=".resize-triggers{visibility:hidden;opacity:0;pointer-events:none}.resize-contract-trigger,.resize-contract-trigger:before,.resize-expand-trigger,.resize-triggers{content:\"\";position:absolute;top:0;left:0;height:100%;width:100%;overflow:hidden}.resize-contract-trigger,.resize-expand-trigger{background:#eee;overflow:auto}.resize-contract-trigger:before{width:200%;height:200%}";var total=0;var style=null;function addListener(elem,callback){if(!elem.__resize_mutation_handler__){elem.__resize_mutation_handler__=handleMutation.bind(elem);}var listeners=elem.__resize_listeners__;if(!listeners){elem.__resize_listeners__=[];if(window.ResizeObserver){var offsetWidth=elem.offsetWidth,offsetHeight=elem.offsetHeight;var ro=new ResizeObserver(function(){if(!elem.__resize_observer_triggered__){elem.__resize_observer_triggered__=true;if(elem.offsetWidth===offsetWidth&&elem.offsetHeight===offsetHeight){return;}}runCallbacks(elem);});// initially display none won't trigger ResizeObserver callback var _getRenderInfo=getRenderInfo(elem),detached=_getRenderInfo.detached,rendered=_getRenderInfo.rendered;elem.__resize_observer_triggered__=detached===false&&rendered===false;elem.__resize_observer__=ro;ro.observe(elem);}else if(elem.attachEvent&&elem.addEventListener){// targeting IE9/10 elem.__resize_legacy_resize_handler__=function handleLegacyResize(){runCallbacks(elem);};elem.attachEvent('onresize',elem.__resize_legacy_resize_handler__);document.addEventListener('DOMSubtreeModified',elem.__resize_mutation_handler__);}else{if(!total){style=createStyles(css);}initTriggers(elem);elem.__resize_rendered__=getRenderInfo(elem).rendered;if(window.MutationObserver){var mo=new MutationObserver(elem.__resize_mutation_handler__);mo.observe(document,{attributes:true,childList:true,characterData:true,subtree:true});elem.__resize_mutation_observer__=mo;}}}elem.__resize_listeners__.push(callback);total++;}function removeListener(elem,callback){var listeners=elem.__resize_listeners__;if(!listeners){return;}if(callback){listeners.splice(listeners.indexOf(callback),1);}// no listeners exist, or removing all listeners if(!listeners.length||!callback){// targeting IE9/10 if(elem.detachEvent&&elem.removeEventListener){elem.detachEvent('onresize',elem.__resize_legacy_resize_handler__);document.removeEventListener('DOMSubtreeModified',elem.__resize_mutation_handler__);return;}if(elem.__resize_observer__){elem.__resize_observer__.unobserve(elem);elem.__resize_observer__.disconnect();elem.__resize_observer__=null;}else{if(elem.__resize_mutation_observer__){elem.__resize_mutation_observer__.disconnect();elem.__resize_mutation_observer__=null;}elem.removeEventListener('scroll',handleScroll);elem.removeChild(elem.__resize_triggers__.triggers);elem.__resize_triggers__=null;}elem.__resize_listeners__=null;}if(! --total&&style){style.parentNode.removeChild(style);}}function getUpdatedSize(elem){var _elem$__resize_last__=elem.__resize_last__,width=_elem$__resize_last__.width,height=_elem$__resize_last__.height;var offsetWidth=elem.offsetWidth,offsetHeight=elem.offsetHeight;if(offsetWidth!==width||offsetHeight!==height){return{width:offsetWidth,height:offsetHeight};}return null;}function handleMutation(){// `this` denotes the scrolling element var _getRenderInfo2=getRenderInfo(this),rendered=_getRenderInfo2.rendered,detached=_getRenderInfo2.detached;if(rendered!==this.__resize_rendered__){if(!detached&&this.__resize_triggers__){resetTriggers(this);this.addEventListener('scroll',handleScroll,true);}this.__resize_rendered__=rendered;runCallbacks(this);}}function handleScroll(){var _this=this;// `this` denotes the scrolling element resetTriggers(this);if(this.__resize_raf__){cancelAnimationFrame(this.__resize_raf__);}this.__resize_raf__=requestAnimationFrame(function(){var updated=getUpdatedSize(_this);if(updated){_this.__resize_last__=updated;runCallbacks(_this);}});}function runCallbacks(elem){if(!elem||!elem.__resize_listeners__){return;}elem.__resize_listeners__.forEach(function(callback){callback.call(elem,elem);});}function initTriggers(elem){var position=getComputedStyle(elem,'position');if(!position||position==='static'){elem.style.position='relative';}elem.__resize_old_position__=position;elem.__resize_last__={};var triggers=createElement('div',{className:'resize-triggers'});var expand=createElement('div',{className:'resize-expand-trigger'});var expandChild=createElement('div');var contract=createElement('div',{className:'resize-contract-trigger'});expand.appendChild(expandChild);triggers.appendChild(expand);triggers.appendChild(contract);elem.appendChild(triggers);elem.__resize_triggers__={triggers:triggers,expand:expand,expandChild:expandChild,contract:contract};resetTriggers(elem);elem.addEventListener('scroll',handleScroll,true);elem.__resize_last__={width:elem.offsetWidth,height:elem.offsetHeight};}function resetTriggers(elem){var _elem$__resize_trigge=elem.__resize_triggers__,expand=_elem$__resize_trigge.expand,expandChild=_elem$__resize_trigge.expandChild,contract=_elem$__resize_trigge.contract;// batch read var csw=contract.scrollWidth,csh=contract.scrollHeight;var eow=expand.offsetWidth,eoh=expand.offsetHeight,esw=expand.scrollWidth,esh=expand.scrollHeight;// batch write contract.scrollLeft=csw;contract.scrollTop=csh;expandChild.style.width=eow+1+'px';expandChild.style.height=eoh+1+'px';expand.scrollLeft=esw;expand.scrollTop=esh;} /***/ }), /***/ 4870: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var _interopRequireDefault=(__webpack_require__(4836)["default"]);Object.defineProperty(exports, "__esModule", ({value:true}));exports["default"]=void 0;var _classCallCheck2=_interopRequireDefault(__webpack_require__(5671));var _createClass2=_interopRequireDefault(__webpack_require__(3144));var _inherits2=_interopRequireDefault(__webpack_require__(9340));var _createSuper2=_interopRequireDefault(__webpack_require__(8557));var _events=__webpack_require__(7187);var _theme=_interopRequireDefault(__webpack_require__(5618));var GlobalEvent=/*#__PURE__*/function(_EventEmitter){(0,_inherits2.default)(GlobalEvent,_EventEmitter);var _super=(0,_createSuper2.default)(GlobalEvent);function GlobalEvent(){var _this;var themValue=arguments.length>0&&arguments[0]!==undefined?arguments[0]:_theme.default[1];(0,_classCallCheck2.default)(this,GlobalEvent);_this=_super.call(this);_this._theme=themValue;return _this;}(0,_createClass2.default)(GlobalEvent,[{key:"theme",get:function get(){return this._theme;},set:function set(themValue){this._theme=themValue;}}]);return GlobalEvent;}(_events.EventEmitter);var _default=new GlobalEvent();exports["default"]=_default; /***/ }), /***/ 9752: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var _interopRequireDefault=(__webpack_require__(4836)["default"]);Object.defineProperty(exports, "__esModule", ({value:true}));exports.callHook=callHook;exports.clearNumberComma=clearNumberComma;exports.getColorWithOpacity=getColorWithOpacity;exports.getComponentInstance=getComponentInstance;exports.getFirstMapTarget=getFirstMapTarget;exports.hexToRgba=hexToRgba;exports.isFunction=isFunction;exports.isXField=isXField;exports.isYField=isYField;exports.reservedDecimal=reservedDecimal;var _colorcolor=_interopRequireDefault(__webpack_require__(9458));// 获取当前时间返回置顶格式 // export function getDateTime(timeType) { // return geti18n().d(new Date(), timeType.replace(/\+/g, '_'), getLanguage()); // } // hex -> rgba function hexToRgba(hex,opacity){return'rgba('+parseInt('0x'+hex.slice(1,3))+','+parseInt('0x'+hex.slice(3,5))+','+parseInt('0x'+hex.slice(5,7))+','+opacity+')';}// export function isTransparent(color) { // const rgba = colorcolor(color, 'rgba'); // return +rgba.match(/(\d(\.\d+)?)+/g)[3] === 0; // } // 保留指定位数的小数 function reservedDecimal(val,precise){return Number(val).toFixed(precise);}// 清除数字(字符串型的)的逗号 function clearNumberComma(num){if(num.replace){num=num.replace(/,/g,'');}return num;}/** * 判断是否地理X坐标 * @param data */function isXField(data){var lowerdata=data.toLowerCase();return lowerdata==='x'||lowerdata==='smx'||lowerdata==='jd'||lowerdata==='经度'||lowerdata==='东经'||lowerdata==='longitude'||lowerdata==='lot'||lowerdata==='lon'||lowerdata==='lng'||lowerdata==='x坐标';}/** * 判断是否地理Y坐标 * @param data */function isYField(data){var lowerdata=data.toLowerCase();return lowerdata==='y'||lowerdata==='smy'||lowerdata==='wd'||lowerdata==='纬度'||lowerdata==='北纬'||lowerdata==='latitude'||lowerdata==='lat'||lowerdata==='y坐标';}function getColorWithOpacity(color,opacity){if(color.indexOf('rgba')>-1){return color.substring(0,color.lastIndexOf(',')+1)+opacity+')';}var newColor=(0,_colorcolor.default)(color,'rgb');return'rgba'+newColor.substring(3,newColor.length-1)+",".concat(opacity,")");}var HOOKS=['loaded','removed'];function callHook(instanceRef,hook,map){HOOKS.includes(hook)&&instanceRef[hook]&&typeof instanceRef[hook]==='function'&&instanceRef[hook](map);}function getComponentInstance(ref){this.instanceRef=ref;}function isFunction(event){return Object.prototype.toString.call(event)==='[object Function]';}function getFirstMapTarget(maps){var firstTarget;for(var key in maps){if(!!key){firstTarget=key;break;}}return firstTarget;} /***/ }), /***/ 7006: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var _interopRequireWildcard=(__webpack_require__(5263)["default"]);var _interopRequireDefault=(__webpack_require__(4836)["default"]);Object.defineProperty(exports, "__esModule", ({value:true}));exports["default"]=withLayer;var _objectSpread2=_interopRequireDefault(__webpack_require__(8683));var _classCallCheck2=_interopRequireDefault(__webpack_require__(5671));var _createClass2=_interopRequireDefault(__webpack_require__(3144));var _assertThisInitialized2=_interopRequireDefault(__webpack_require__(7326));var _inherits2=_interopRequireDefault(__webpack_require__(9340));var _createSuper2=_interopRequireDefault(__webpack_require__(8557));var _wrapDisplayName2=_interopRequireDefault(__webpack_require__(6626));var _react=_interopRequireWildcard(__webpack_require__(3899));var _hoistNonReactStatics=_interopRequireDefault(__webpack_require__(8679));var _lodash=_interopRequireDefault(__webpack_require__(4461));var _lodash2=_interopRequireDefault(__webpack_require__(1633));var _util=__webpack_require__(9752);var _jsxRuntime=__webpack_require__(5893);function withLayer(WrappedComponent){var BaseLayer=/*#__PURE__*/function(_PureComponent){(0,_inherits2.default)(BaseLayer,_PureComponent);var _super=(0,_createSuper2.default)(BaseLayer);function BaseLayer(props){var _this;(0,_classCallCheck2.default)(this,BaseLayer);_this=_super.call(this,props);_this.registerEvents=[];_this.$_emitEvent=function(name){var data=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};var originEventName="on".concat((0,_lodash2.default)(name));if((0,_util.isFunction)(_this.props[originEventName])){_this.props[originEventName]((0,_objectSpread2.default)({map:_this.map,layerId:_this.props.layerId},data));}};_this.$_emitLayerMapEvent=function(event){_this.$_emitEvent(event.type,{mapboxEvent:event});};_this.$_bindLayerEvents=function(){Object.keys(_this.props).forEach(function(eventName){if(_this.eventList.includes(eventName)){var layerId=_this.props.layerId;// @ts-ignore var layer=_this.map.overlayLayersManager[layerId];var name=eventName.replace('on','');var registerEventName=name.toLowerCase();_this.registerEvents.push(registerEventName);if(layer){_this.overLayer=layer;layer.on(registerEventName,_this.$_emitLayerMapEvent);}else{_this.map.on(registerEventName,layerId,_this.$_emitLayerMapEvent);}}});};_this.$_unbindLayerEvents=function(events){if(_this.map){events.forEach(function(eventName){!_this.overLayer&&_this.map.off(eventName,_this.props.layerId,_this.$_emitLayerMapEvent);});}};// move = beforeId => { // this.map.moveLayer(this.props.layerId, beforeId); // this.$_emitEvent('layer-moved', { // beforeId: beforeId // }); // }; _this.remove=function(){var layerId=arguments.length>0&&arguments[0]!==undefined?arguments[0]:_this.props.layerId;if(_this.registerEvents&&_this.registerEvents.length){_this.$_unbindLayerEvents(_this.registerEvents);}if(_this.map){_this.map&&_this.map.removeLayer(layerId);_this.$_emitEvent('layer-removed');}};_this.eventList=['onMousedown','onMouseup','onClick','onDblclick','onMousemove','onMouseenter','onMouseleave','onMouseover','onMouseout','onContextmenu','onTouchstart','onTouchend','onTouchcancel'];_this.getComponentInstance=_util.getComponentInstance.bind((0,_assertThisInitialized2.default)(_this));return _this;}(0,_createClass2.default)(BaseLayer,[{key:"componentDidUpdate",value:function componentDidUpdate(prevProps){if(prevProps.minzoom!==this.props.minzoom||prevProps.maxzoom!==this.props.maxzoom){this.map.setLayerZoomRange(this.props.layerId,this.props.minzoom,this.props.maxzoom);}if(prevProps.filter!==this.props.filter){this.map.setFilter(this.props.layerId,this.props.filter);}if(this.props.layout&&prevProps.layout!==this.props.layout){for(var _i=0,_Object$keys=Object.keys(this.props.layout);_i<_Object$keys.length;_i++){var prop=_Object$keys[_i];this.map.setLayoutProperty(this.props.layerId,prop,this.props.layout[prop]);}}if(this.props.paint&&prevProps.paint!==this.props.paint){for(var _i2=0,_Object$keys2=Object.keys(this.props.paint);_i2<_Object$keys2.length;_i2++){var _prop=_Object$keys2[_i2];this.map.setPaintProperty(this.props.layerId,_prop,this.props.paint[_prop]);}}if(this.props.metadata&&prevProps.metadata!==this.props.metadata){var layer=this.map.getLayer(this.props.layerId),metadata=layer.metadata;if(metadata){Object.assign(layer.metadata,this.props.metadata);}else{layer.metadata=this.props.metadata;}}}},{key:"componentWillUnmount",value:function componentWillUnmount(){this.remove();}},{key:"loaded",value:function loaded(map){this.map=map;(0,_util.callHook)(this.instanceRef,'loaded',this.map);this.$_bindLayerEvents();}},{key:"removed",value:function removed(map){if(this.props.layerId&&this.map){this.remove();}this.map=map;(0,_util.callHook)(this.instanceRef,'removed',this.map);}},{key:"render",value:function render(){// const { layerId } = this.props; // const id = source || layerId; // const sourceLoaded = // this.map && layerId ? this.map.isSourceLoaded(layerId) : false; // const mapLayer = this.map ? this.map.getLayer(layerId) : null; // const mapSource = // this.map && layerId ? this.map.getSource(layerId) : null; var newProps=Object.assign({},this.props,{// sourceLoaded, // mapLayer, // mapSource });return/*#__PURE__*/(0,_jsxRuntime.jsx)(WrappedComponent,(0,_objectSpread2.default)((0,_objectSpread2.default)({},newProps),{},{ref:this.getComponentInstance,remove:this.remove}));}}]);return BaseLayer;}(_react.PureComponent);BaseLayer.displayName=(0,_wrapDisplayName2.default)(WrappedComponent,'withLayer');BaseLayer.defaultProps={layerId:(0,_lodash.default)("".concat(WrappedComponent.name.toLowerCase(),"-")),minzoom:0,maxzoom:22};;return(0,_hoistNonReactStatics.default)(BaseLayer,WrappedComponent);}; /***/ }), /***/ 9635: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var _interopRequireDefault=(__webpack_require__(4836)["default"]);Object.defineProperty(exports, "__esModule", ({value:true}));exports["default"]=mapGetter;var _objectSpread2=_interopRequireDefault(__webpack_require__(8683));var _classCallCheck2=_interopRequireDefault(__webpack_require__(5671));var _createClass2=_interopRequireDefault(__webpack_require__(3144));var _assertThisInitialized2=_interopRequireDefault(__webpack_require__(7326));var _inherits2=_interopRequireDefault(__webpack_require__(9340));var _createSuper2=_interopRequireDefault(__webpack_require__(8557));var _wrapDisplayName2=_interopRequireDefault(__webpack_require__(6626));var _react=_interopRequireDefault(__webpack_require__(3899));var _hoistNonReactStatics=_interopRequireDefault(__webpack_require__(8679));var _antd=__webpack_require__(2721);var _mapEvent=_interopRequireDefault(__webpack_require__(1104));var _globalEvent=_interopRequireDefault(__webpack_require__(4870));var _util=__webpack_require__(9752);var _jsxRuntime=__webpack_require__(5893);function mapGetter(WrappedComponent){var MapGetter=/*#__PURE__*/function(_React$Component){(0,_inherits2.default)(MapGetter,_React$Component);var _super=(0,_createSuper2.default)(MapGetter);function MapGetter(props){var _this;(0,_classCallCheck2.default)(this,MapGetter);_this=_super.call(this,props);_this.loadMapSucceed=_this.loadMapSucceed.bind((0,_assertThisInitialized2.default)(_this));_this.deleteMapSucceed=_this.deleteMapSucceed.bind((0,_assertThisInitialized2.default)(_this));_this.getComponentInstance=_util.getComponentInstance.bind((0,_assertThisInitialized2.default)(_this));return _this;}(0,_createClass2.default)(MapGetter,[{key:"componentDidMount",value:function componentDidMount(){var targetName=this.getTargetName();if(_mapEvent.default.getMap(targetName)){this.loadMap(targetName);}_mapEvent.default.on('load-map',this.loadMapSucceed);_globalEvent.default.on('delete-map',this.deleteMapSucceed);}},{key:"componentDidUpdate",value:function componentDidUpdate(prevProps){var mapTarget=this.props.mapTarget;var prevMapTarget=prevProps.mapTarget;if(mapTarget&&prevMapTarget&&mapTarget!==prevMapTarget){this.mapTargetChanged(mapTarget);}}},{key:"componentWillUnmount",value:function componentWillUnmount(){_mapEvent.default.off('load-map',this.loadMapSucceed);_globalEvent.default.off('delete-map',this.deleteMapSucceed);}},{key:"getTargetName",value:function getTargetName(){/** * 便于区分存在多个map时,子组件对应的map的渲染; * map 和 webmap 的 props 属性是 target 其他组件都叫 mapTarget * 如果子组件包裹在 map 组件里面,若没有传 mapTarget, 则 targetName 直接取父元素的target 的值 * 如果子组件和 map 同层级,且没有设置 mapTarget 时,则默认渲染到第一个 map 上 * */ // const selfParent = this._reactInternalInstance._currentElement._owner._instance; // console.log(selfParent); // console.log('selfParent: ', selfParent); // const parentTarget = // selfParent && selfParent.name.toLowerCase() === 'smwebmap' && // selfParent.target; // return this.props.mapTarget || parentTarget || Object.keys(mapEvent.getAllMaps())[0]; var maps=_mapEvent.default.getAllMaps();return this.props.mapTarget||(0,_util.getFirstMapTarget)(maps);}},{key:"loadMapSucceed",value:function loadMapSucceed(map,target){var targetName=this.getTargetName();if(target===targetName){this.loadMap(target);}}},{key:"mapTargetChanged",value:function mapTargetChanged(target){// 多个map切换的时候,需要删除该组件与前一个map的图层绑定, 如果新的target没有对应的map,那么默认绑定第一个地图 var maps=_mapEvent.default.getAllMaps();var targetName=(0,_util.getFirstMapTarget)(maps);var firstMap=_mapEvent.default.getMap(targetName);this.resetData();if(_mapEvent.default.getMap(target)||firstMap){this.loadMap(target);}}},{key:"loadMap",value:function loadMap(targetName){this.map=_mapEvent.default.getMap(targetName);this.webmap=_mapEvent.default.getWebMap(targetName);(0,_util.callHook)(this.instanceRef,'loaded',this.map);// 控制与map组件同级的组件的显示加载 // setTimeout(() => { // /** // * @event loaded // * @desc 组件加载渲染完成之后触发。 // */ // this.$emit('loaded'); // }, 0); }},{key:"deleteMapSucceed",value:function deleteMapSucceed(target){var targetName=this.getTargetName();if(target===targetName){this.resetData();}}},{key:"resetData",value:function resetData(){this.map=null;this.webmap=null;(0,_util.callHook)(this.instanceRef,'removed',this.map);}},{key:"mapNotLoadedTip",value:function mapNotLoadedTip(){if(!this.map){_antd.message.destroy();// TODO // message.warning(this.$t('warning.unassociatedMap')); _antd.message.warning('您需要配置关联地图!');return true;}return false;}},{key:"render",value:function render(){return/*#__PURE__*/(0,_jsxRuntime.jsx)(WrappedComponent,(0,_objectSpread2.default)((0,_objectSpread2.default)({},this.props),{},{ref:this.getComponentInstance,mapNotLoadedTip:this.mapNotLoadedTip}));}}]);return MapGetter;}(_react.default.Component);MapGetter.displayName=(0,_wrapDisplayName2.default)(WrappedComponent,'mapGetter');return(0,_hoistNonReactStatics.default)(MapGetter,WrappedComponent);} /***/ }), /***/ 1558: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var _interopRequireDefault=(__webpack_require__(4836)["default"]);Object.defineProperty(exports, "__esModule", ({value:true}));exports["default"]=void 0;var _createClass2=_interopRequireDefault(__webpack_require__(3144));var _classCallCheck2=_interopRequireDefault(__webpack_require__(5671));/** * @class CircleStyle * @category BaseTypes Style * @classdesc 点图层样式类。 * @param {mapboxgl.LayersCircle} paint - MapboxGL 点图层 Paint 配置。 * @param {mapboxgl.LayersCircle} layout - MapboxGL 点图层 Layout 配置。 */var CircleStyle=/*#__PURE__*/(0,_createClass2.default)(function CircleStyle(){var paint=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{};var layout=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};(0,_classCallCheck2.default)(this,CircleStyle);this.layout={visibility:'visible'};this.paint={'circle-radius':6,'circle-color':'#3fb1e3','circle-opacity':1,'circle-blur':0,'circle-translate':[0,0],'circle-translate-anchor':'map','circle-pitch-scale':'map','circle-pitch-alignment':'viewport','circle-stroke-width':0,'circle-stroke-color':'#000','circle-stroke-opacity':1};Object.assign(this.paint,paint);Object.assign(this.layout,layout);});exports["default"]=CircleStyle; /***/ }), /***/ 3768: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var _interopRequireDefault=(__webpack_require__(4836)["default"]);Object.defineProperty(exports, "__esModule", ({value:true}));exports["default"]=void 0;var _createClass2=_interopRequireDefault(__webpack_require__(3144));var _classCallCheck2=_interopRequireDefault(__webpack_require__(5671));/** * @class FillStyle * @category BaseTypes Style * @classdesc 面图层样式类。 * @param {mapboxgl.LayersFill} paint - MapboxGL 面图层 Paint 配置。 * @param {mapboxgl.LayersFill} layout - MapboxGL 面图层 Layout 配置。 */var FillStyle=/*#__PURE__*/(0,_createClass2.default)(function FillStyle(){var paint=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{};var layout=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};(0,_classCallCheck2.default)(this,FillStyle);this.layout={visibility:'visible'};this.paint={'fill-opacity':0.8,'fill-color':'#3fb1e3','fill-translate':[0,0],'fill-antialias':true,'fill-outline-color':'#3fb1e3','fill-translate-anchor':'map'};Object.assign(this.paint,paint);Object.assign(this.layout,layout);});exports["default"]=FillStyle; /***/ }), /***/ 9623: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var _interopRequireDefault=(__webpack_require__(4836)["default"]);Object.defineProperty(exports, "__esModule", ({value:true}));exports["default"]=void 0;var _createClass2=_interopRequireDefault(__webpack_require__(3144));var _classCallCheck2=_interopRequireDefault(__webpack_require__(5671));var HeatMapStyle=/*#__PURE__*/(0,_createClass2.default)(function HeatMapStyle(){var paint=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{};var layout=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};(0,_classCallCheck2.default)(this,HeatMapStyle);this.paint={'heatmap-radius':30,'heatmap-weight':1,'heatmap-intensity':1,'heatmap-color':['interpolate',['linear'],['heatmap-density'],0,'rgba(0, 0, 255, 0)',0.1,'royalblue',0.3,'cyan',0.5,'lime',0.7,'yellow',1,'red'],'heatmap-opacity':1};this.layout={visibility:'visible'};Object.assign(this.paint,paint);Object.assign(this.layout,layout);});exports["default"]=HeatMapStyle; /***/ }), /***/ 8214: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var _interopRequireDefault=(__webpack_require__(4836)["default"]);Object.defineProperty(exports, "__esModule", ({value:true}));exports["default"]=void 0;var _createClass2=_interopRequireDefault(__webpack_require__(3144));var _classCallCheck2=_interopRequireDefault(__webpack_require__(5671));/** * @class LineStyle * @category BaseTypes Style * @classdesc 线图层样式类。 * @param {mapboxgl.LayersLine} paint - MapboxGL 线图层 Paint 配置。 * @param {mapboxgl.LayersLine} layout - MapboxGL 线图层 Layout 配置。 */var LineStyle=/*#__PURE__*/(0,_createClass2.default)(function LineStyle(){var paint=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{};var layout=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};(0,_classCallCheck2.default)(this,LineStyle);this.layout={visibility:'visible','line-cap':'butt','line-join':'miter'};this.paint={'line-opacity':1,'line-color':'#3fb1e3','line-width':3,'line-blur':1};Object.assign(this.paint,paint);Object.assign(this.layout,layout);});exports["default"]=LineStyle; /***/ }), /***/ 1700: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var _interopRequireDefault=(__webpack_require__(4836)["default"]);Object.defineProperty(exports, "__esModule", ({value:true}));exports["default"]=void 0;var _createClass2=_interopRequireDefault(__webpack_require__(3144));var _classCallCheck2=_interopRequireDefault(__webpack_require__(5671));/** * @class SymbolStyle * @classdesc symbol 图层样式类。 */var SymbolStyle=/*#__PURE__*/(0,_createClass2.default)(function SymbolStyle(){var paint=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{};var layout=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};(0,_classCallCheck2.default)(this,SymbolStyle);this.paint=Object.assign({},paint);this.layout=Object.assign({visibility:'visible'},layout);});exports["default"]=SymbolStyle; /***/ }), /***/ 2009: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var _interopRequireDefault=(__webpack_require__(4836)["default"]);Object.defineProperty(exports, "__esModule", ({value:true}));Object.defineProperty(exports, "CircleStyle", ({enumerable:true,get:function get(){return _CircleStyle.default;}}));Object.defineProperty(exports, "FillStyle", ({enumerable:true,get:function get(){return _FillStyle.default;}}));Object.defineProperty(exports, "HeatMapStyle", ({enumerable:true,get:function get(){return _HeatMapStyle.default;}}));Object.defineProperty(exports, "LineStyle", ({enumerable:true,get:function get(){return _LineStyle.default;}}));Object.defineProperty(exports, "SymbolStyle", ({enumerable:true,get:function get(){return _SymbolStyle.default;}}));var _CircleStyle=_interopRequireDefault(__webpack_require__(1558));var _FillStyle=_interopRequireDefault(__webpack_require__(3768));var _LineStyle=_interopRequireDefault(__webpack_require__(8214));var _HeatMapStyle=_interopRequireDefault(__webpack_require__(9623));var _SymbolStyle=_interopRequireDefault(__webpack_require__(1700)); /***/ }), /***/ 1104: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var _interopRequireDefault=(__webpack_require__(4836)["default"]);Object.defineProperty(exports, "__esModule", ({value:true}));exports["default"]=void 0;var _classCallCheck2=_interopRequireDefault(__webpack_require__(5671));var _createClass2=_interopRequireDefault(__webpack_require__(3144));var _inherits2=_interopRequireDefault(__webpack_require__(9340));var _createSuper2=_interopRequireDefault(__webpack_require__(8557));var _events=__webpack_require__(7187);var _SourceListModel=_interopRequireDefault(__webpack_require__(8383));var _globalEvent=_interopRequireDefault(__webpack_require__(4870));var MapEvent=/*#__PURE__*/function(_EventEmitter){(0,_inherits2.default)(MapEvent,_EventEmitter);var _super=(0,_createSuper2.default)(MapEvent);function MapEvent(){var _this;(0,_classCallCheck2.default)(this,MapEvent);for(var _len=arguments.length,args=new Array(_len),_key=0;_key<_len;_key++){args[_key]=arguments[_key];}_this=_super.call.apply(_super,[this].concat(args));_this.mapCache={};_this.webMapCache={};return _this;}(0,_createClass2.default)(MapEvent,[{key:"getMap",value:function getMap(mapTarget){return this.mapCache[mapTarget];}},{key:"getWebMap",value:function getWebMap(webmapTarget){return this.webMapCache[webmapTarget];}},{key:"getAllMaps",value:function getAllMaps(){return this.mapCache;}},{key:"getAllWebMap",value:function getAllWebMap(){return this.webMapCache;}},{key:"setMap",value:function setMap(mapTarget,map){this.mapCache[mapTarget]=map;}},{key:"setWebMap",value:function setWebMap(webmapTarget,webmap){this.webMapCache[webmapTarget]=webmap;}},{key:"deleteMap",value:function deleteMap(mapTarget){_globalEvent.default.emit('delete-map',mapTarget);// drawEvent.$options.deletDrawOfMap(mapTarget); delete this.mapCache[mapTarget];}},{key:"deleteWebMap",value:function deleteWebMap(webmapTarget){delete this.webMapCache[webmapTarget];}},{key:"getMapSource",value:function getMapSource(mapTarget){var sources=[];var map=this.getMap(mapTarget);if(map){var sourceListModel=new _SourceListModel.default({map:map});var sourceList=sourceListModel.getSourceList();for(var key in sourceList){if(key){var layers=sourceList[key].layers||[];layers.forEach(function(item){if(item.source&&item.type!=='raster'){sources.push(item.source);}});}}}return sources;}}]);return MapEvent;}(_events.EventEmitter);var _default=new MapEvent();exports["default"]=_default; /***/ }), /***/ 3595: /***/ (function(__unused_webpack_module, exports) { "use strict"; Object.defineProperty(exports, "__esModule", ({value:true}));exports.handleMultyPolygon=void 0;var handleMultyPolygon=function handleMultyPolygon(features){features.forEach(function(feature){if(feature.geometry.type!=='Polygon'){return;}var coords=feature.geometry.coordinates;if(coords.length>1){var coordinates=[];coords.forEach(function(coord){coordinates.push([coord]);});feature.geometry.coordinates=coordinates;feature.geometry.type='MultiPolygon';}});return features;};exports.handleMultyPolygon=handleMultyPolygon; /***/ }), /***/ 1191: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var _interopRequireDefault=(__webpack_require__(4836)["default"]);Object.defineProperty(exports, "__esModule", ({value:true}));Object.defineProperty(exports, "SmAnimateMarkerLayer", ({enumerable:true,get:function get(){return _AnimateMarkerLayer.default;}}));Object.defineProperty(exports, "SmClusterLayer", ({enumerable:true,get:function get(){return _ClusterLayer.default;}}));Object.defineProperty(exports, "SmDataFlowLayer", ({enumerable:true,get:function get(){return _DataFlowLayer.default;}}));Object.defineProperty(exports, "SmDeckglLayer", ({enumerable:true,get:function get(){return _DeckglLayer.default;}}));Object.defineProperty(exports, "SmEchartsLayer", ({enumerable:true,get:function get(){return _EchartsLayer.default;}}));Object.defineProperty(exports, "SmFireLayer", ({enumerable:true,get:function get(){return _FireLayer.default;}}));Object.defineProperty(exports, "SmGeojsonLayer", ({enumerable:true,get:function get(){return _GeojsonLayer.default;}}));Object.defineProperty(exports, "SmGraphThemeLayer", ({enumerable:true,get:function get(){return _GraphThemeLayer.default;}}));Object.defineProperty(exports, "SmHeatmapLayer", ({enumerable:true,get:function get(){return _HeatmapLayer.default;}}));Object.defineProperty(exports, "SmLabelThemeLayer", ({enumerable:true,get:function get(){return _LabelThemeLayer.default;}}));Object.defineProperty(exports, "SmLayer", ({enumerable:true,get:function get(){return _Layer.default;}}));Object.defineProperty(exports, "SmMap", ({enumerable:true,get:function get(){return _Map.default;}}));Object.defineProperty(exports, "SmMapvLayer", ({enumerable:true,get:function get(){return _MapvLayer.default;}}));Object.defineProperty(exports, "SmRangeThemeLayer", ({enumerable:true,get:function get(){return _RangeThemeLayer.default;}}));Object.defineProperty(exports, "SmRanksymbolThemeLayer", ({enumerable:true,get:function get(){return _RanksymbolThemeLayer.default;}}));Object.defineProperty(exports, "SmRasterTileLayer", ({enumerable:true,get:function get(){return _RasterTileLayer.default;}}));Object.defineProperty(exports, "SmSource", ({enumerable:true,get:function get(){return _Source.default;}}));Object.defineProperty(exports, "SmUniqueThemeLayer", ({enumerable:true,get:function get(){return _UniqueThemeLayer.default;}}));Object.defineProperty(exports, "SmVectorTileLayer", ({enumerable:true,get:function get(){return _VectorTileLayer.default;}}));Object.defineProperty(exports, "SmWebMap", ({enumerable:true,get:function get(){return _WebMap.default;}}));var _WebMap=_interopRequireDefault(__webpack_require__(4416));var _Map=_interopRequireDefault(__webpack_require__(8611));var _Source=_interopRequireDefault(__webpack_require__(1406));var _Layer=_interopRequireDefault(__webpack_require__(5558));var _GeojsonLayer=_interopRequireDefault(__webpack_require__(9704));var _RasterTileLayer=_interopRequireDefault(__webpack_require__(1771));var _VectorTileLayer=_interopRequireDefault(__webpack_require__(2125));var _UniqueThemeLayer=_interopRequireDefault(__webpack_require__(4204));var _RanksymbolThemeLayer=_interopRequireDefault(__webpack_require__(3930));var _RangeThemeLayer=_interopRequireDefault(__webpack_require__(5890));var _GraphThemeLayer=_interopRequireDefault(__webpack_require__(910));var _ClusterLayer=_interopRequireDefault(__webpack_require__(9407));var _DeckglLayer=_interopRequireDefault(__webpack_require__(9183));var _LabelThemeLayer=_interopRequireDefault(__webpack_require__(2174));var _HeatmapLayer=_interopRequireDefault(__webpack_require__(6073));var _MapvLayer=_interopRequireDefault(__webpack_require__(7));var _EchartsLayer=_interopRequireDefault(__webpack_require__(1762));var _DataFlowLayer=_interopRequireDefault(__webpack_require__(2313));var _FireLayer=_interopRequireDefault(__webpack_require__(4799));var _AnimateMarkerLayer=_interopRequireDefault(__webpack_require__(1193)); /***/ }), /***/ 4483: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var _interopRequireWildcard=(__webpack_require__(5263)["default"]);var _interopRequireDefault=(__webpack_require__(4836)["default"]);Object.defineProperty(exports, "__esModule", ({value:true}));var _exportNames={};exports["default"]=void 0;var _objectSpread2=_interopRequireDefault(__webpack_require__(8683));__webpack_require__(9626);__webpack_require__(2547);var components=_interopRequireWildcard(__webpack_require__(1191));Object.keys(components).forEach(function(key){if(key==="default"||key==="__esModule")return;if(Object.prototype.hasOwnProperty.call(_exportNames,key))return;if(key in exports&&exports[key]===components[key])return;Object.defineProperty(exports,key,{enumerable:true,get:function get(){return components[key];}});});var commontypes=_interopRequireWildcard(__webpack_require__(2009));var exportData=(0,_objectSpread2.default)((0,_objectSpread2.default)({},components),{},{commontypes:commontypes});var _default=exportData;exports["default"]=_default; /***/ }), /***/ 1016: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var _interopRequireDefault=(__webpack_require__(4836)["default"]);Object.defineProperty(exports, "__esModule", ({value:true}));exports["default"]=void 0;var _createClass2=_interopRequireDefault(__webpack_require__(3144));var _classCallCheck2=_interopRequireDefault(__webpack_require__(5671));/** * @class LayerModel * @description 图层数据模型。 * @param {Object} options - 图层参数。 * @param {String} [options.id] - 图层 ID。 * @param {Number} [options.maxzoom] - 最大缩放级别。 * @param {Number} [options.minzoom] - 最小缩放级别。 * @param {GeoJSONObject} [options.source] - 数据源。 * @param {String} [options.type] - 图层类型。 * @param {String} [options.visibility] - 图层是否可见。 * @category Model */var LayerModel=/*#__PURE__*/(0,_createClass2.default)(function LayerModel(){var options=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{};(0,_classCallCheck2.default)(this,LayerModel);this.id=options.id;this.maxzoom=options.maxzoom;this.minzoom=options.minzoom;this.source=options.source;this.type=options.type;this.visibility=options.visibility||'visible';});var _default=LayerModel;exports["default"]=_default; /***/ }), /***/ 8611: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var _interopRequireWildcard=(__webpack_require__(5263)["default"]);var _interopRequireDefault=(__webpack_require__(4836)["default"]);Object.defineProperty(exports, "__esModule", ({value:true}));exports["default"]=void 0;var _objectSpread2=_interopRequireDefault(__webpack_require__(8683));var _classCallCheck2=_interopRequireDefault(__webpack_require__(5671));var _createClass2=_interopRequireDefault(__webpack_require__(3144));var _assertThisInitialized2=_interopRequireDefault(__webpack_require__(7326));var _inherits2=_interopRequireDefault(__webpack_require__(9340));var _createSuper2=_interopRequireDefault(__webpack_require__(8557));var _react=_interopRequireWildcard(__webpack_require__(3899));var _interface=__webpack_require__(4831);var _MapViewModal=_interopRequireDefault(__webpack_require__(8031));var _lodash=_interopRequireDefault(__webpack_require__(1296));var _lodash2=_interopRequireDefault(__webpack_require__(1633));var _lodash3=_interopRequireDefault(__webpack_require__(39));var _lodash4=_interopRequireDefault(__webpack_require__(9208));var _lodash5=_interopRequireDefault(__webpack_require__(2307));var _resizeDetector=__webpack_require__(1892);var _mapEvent=_interopRequireDefault(__webpack_require__(1104));var _util=__webpack_require__(9752);var _jsxRuntime=__webpack_require__(5893);var Map=/*#__PURE__*/function(_Component){(0,_inherits2.default)(Map,_Component);var _super=(0,_createSuper2.default)(Map);function Map(props){var _this;(0,_classCallCheck2.default)(this,Map);_this=_super.call(this,props);_this.viewModelProps=['mapOptions.center','mapOptions.zoom','mapOptions.crs','mapOptions.minZoom','mapOptions.maxZoom','mapOptions.maxBounds','mapOptions.renderWorldCopies','mapOptions.bearing','mapOptions.pitch'];_this.initializeWebMap=function(){var _this$props=_this.props,target=_this$props.target,tiandituKey=_this$props.tiandituKey,mapOptions=_this$props.mapOptions,autoresize=_this$props.autoresize;_this.viewModel=new _MapViewModal.default({target:target,tiandituKey:tiandituKey},mapOptions);if(autoresize){(0,_resizeDetector.addListener)(_this.selfRef.current,_this.__resizeHandler);}};_this.registerEvents=function(){var _this$props2=_this.props,target=_this$props2.target,onLoad=_this$props2.onLoad;_this.viewModel.on('addlayerssucceeded',function(e){_this.setState({spinning:false});_mapEvent.default.setMap(target,e.map);_this.viewModel&&_mapEvent.default.setWebMap(target,_this.viewModel);_mapEvent.default.emit('load-map',e.map,target);e.map.resize();_this.map=e.map;if(false){}// 绑定map event _this.bindMapEvents();/** * @event load * @desc webmap 加载完成之后触发。 * @property {mapboxgl.Map} map - MapBoxGL Map 对象。 */(0,_util.isFunction)(onLoad)&&onLoad((0,_objectSpread2.default)((0,_objectSpread2.default)({},e),{},{component:(0,_assertThisInitialized2.default)(_this)}));});};_this.mapEventCallback=function(event){var data=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};_this.emitMapEvent(event.type,(0,_objectSpread2.default)({mapboxEvent:event},data));};_this.state={spinning:true};_this.selfRef=/*#__PURE__*/_react.default.createRef();_this.__resizeHandler=(0,_lodash.default)(_this.__resizeHandler.bind((0,_assertThisInitialized2.default)(_this)),100,{leading:true});return _this;}(0,_createClass2.default)(Map,[{key:"componentDidMount",value:function componentDidMount(){this.initializeWebMap();this.registerEvents();}},{key:"getLayerIds",value:function getLayerIds(children){return children===null||children===void 0?void 0:children.reduce(function(layerIds,child){var _child$type,_child$type$displayNa;if(child!==null&&child!==void 0&&(_child$type=child.type)!==null&&_child$type!==void 0&&(_child$type$displayNa=_child$type.displayName)!==null&&_child$type$displayNa!==void 0&&_child$type$displayNa.includes('Layer')){var id=child.props.layerId;id&&layerIds.push(id);}return layerIds;},[]);}},{key:"componentDidUpdate",value:function componentDidUpdate(prevProps){var _this2=this;this.viewModel&&this.viewModelProps.forEach(function(prop){var name=prop.includes('.')?prop.split('.')[1]:prop;var funcName="set".concat((0,_lodash3.default)(name));var propsValue=(0,_lodash4.default)(_this2.props,prop);var prevPropsValue=(0,_lodash4.default)(prevProps,prop);if(propsValue&&!(0,_lodash5.default)(propsValue,prevPropsValue)){_this2.viewModel[funcName](propsValue);}});var _this$props3=this.props,sprites=_this$props3.sprites,glyphs=_this$props3.glyphs;for(var id in sprites){if(prevProps.sprites[id]!==sprites[id]){this.viewModel.addSprites(id,sprites[id]);}}for(var _id2 in glyphs){if(prevProps.glyphs[_id2]!==glyphs[_id2]){this.viewModel.addGlyphs(_id2,glyphs[_id2]);}}if(!this.map){return;}var preLayerIds=this.getLayerIds(prevProps.children);var newLayerIds=this.getLayerIds(this.props.children);// 过滤图层顺序相等的情况 if(!(0,_lodash5.default)(preLayerIds,newLayerIds)){this.viewModel.changeLayersOrder(newLayerIds);}}},{key:"componentWillUnmount",value:function componentWillUnmount(){var _this$props4=this.props,target=_this$props4.target,autoresize=_this$props4.autoresize;_mapEvent.default.deleteMap(target);_mapEvent.default.deleteWebMap(target);if(autoresize&&this.selfRef.current){(0,_resizeDetector.removeListener)(this.selfRef.current,this.__resizeHandler);}}},{key:"bindMapEvents",value:function bindMapEvents(){var _this3=this;Object.keys(this.props).forEach(function(eventName){if(_interface.MAP_EVENT_NAMES.includes(eventName)){var name=eventName.replace('on','');_this3.bindMapEvent(name.toLowerCase(),_this3.mapEventCallback);}});}},{key:"bindMapEvent",value:function bindMapEvent(eventName,eventCallback){this.map.on(eventName,eventCallback);}},{key:"emitMapEvent",value:function emitMapEvent(name){var data=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};var originEventName="on".concat((0,_lodash2.default)(name));if((0,_util.isFunction)(this.props[originEventName])){this.props[originEventName]((0,_objectSpread2.default)({map:this.map,component:this},data));}}},{key:"__resizeHandler",value:function __resizeHandler(){this.resize();}},{key:"resize",value:function resize(){if(this.viewModel&&this.viewModel.resize){this.viewModel.resize();}}},{key:"render",value:function render(){var spinning=this.state.spinning;var _this$props5=this.props,target=_this$props5.target,children=_this$props5.children;return/*#__PURE__*/(0,_jsxRuntime.jsx)("div",{id:target,className:"sm-component-map",ref:this.selfRef,children:!spinning&&children});}}]);return Map;}(_react.Component);Map.defaultProps={target:'map',autoresize:true};var _default=Map;exports["default"]=_default; /***/ }), /***/ 8031: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var _interopRequireDefault=(__webpack_require__(4836)["default"]);Object.defineProperty(exports, "__esModule", ({value:true}));exports["default"]=void 0;var _classCallCheck2=_interopRequireDefault(__webpack_require__(5671));var _createClass2=_interopRequireDefault(__webpack_require__(3144));var _inherits2=_interopRequireDefault(__webpack_require__(9340));var _createSuper2=_interopRequireDefault(__webpack_require__(8557));var _mapboxGlEnhance=_interopRequireDefault(__webpack_require__(375));var MapViewModal=/*#__PURE__*/function(_mapboxgl$Evented){(0,_inherits2.default)(MapViewModal,_mapboxgl$Evented);var _super=(0,_createSuper2.default)(MapViewModal);function MapViewModal(options){var _this;var mapOptions=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{style:{version:8,sources:{},layers:[]}};(0,_classCallCheck2.default)(this,MapViewModal);_this=_super.call(this);_this.mapOptions=Object.assign({style:{version:8,sources:{},layers:[]}},mapOptions);_this.tiandituKey=options.tiandituKey||'';_this.target=options.target||'map';_this.center=mapOptions.center||[];_this.zoom=mapOptions.zoom;_this._createMap();return _this;}(0,_createClass2.default)(MapViewModal,[{key:"_createMap",value:function _createMap(){var _this2=this;if(this.map){this.map.remove();this.center=[];this.zoom=null;}this.mapOptions.container=this.target;setTimeout(function(){_this2.map=new _mapboxGlEnhance.default.Map(_this2.mapOptions);_this2.map.on('load',function(){_this2.fire('addlayerssucceeded',{map:_this2.map});});},0);return;}/** * @function WebMapViewModel.prototype.resize * @description Map 更新大小。 */},{key:"resize",value:function resize(){this.map&&this.map.resize();}/** * @function WebMapViewModel.prototype.setCRS * @description 设置地图的投影。 * @param {Number} crs - 地图投影。 */},{key:"setCrs",value:function setCrs(crs){if(this.map){this.mapOptions.crs=crs;//@ts-ignore crs&&this.map.setCRS(_mapboxGlEnhance.default.CRS.get(crs));}}/** * @function WebMapViewModel.prototype.setZoom * @description 设置地图的缩放级别。 * @param {Number} zoom - 地图缩放级别。 */},{key:"setZoom",value:function setZoom(zoom){if(this.map){this.mapOptions.zoom=zoom;(zoom||zoom===0)&&this.map.setZoom(zoom);}}/** * @function WebMapViewModel.prototype.setCenter * @description 设置地图的中心点。 * @param {Array} center - 地图中心点。 */},{key:"setCenter",value:function setCenter(center){if(this.map){this.mapOptions.center=center;center&¢er.length>0&&this.map.setCenter(center);}}/** * @function WebMapViewModel.prototype.setMaxBounds * @description 设置地图的最大范围。 * @param {Array} maxBounds - 地图最大范围。 */},{key:"setMaxBounds",value:function setMaxBounds(maxBounds){if(this.map){this.mapOptions.maxBounds=maxBounds;maxBounds&&maxBounds.length>0&&this.map.setMaxBounds(maxBounds);}}/** * @function WebMapViewModel.prototype.setMinZoom * @description 设置地图的最小级别。 * @param {Number} minZoom - 地图最小级别。 */},{key:"setMinZoom",value:function setMinZoom(minZoom){if(this.map){this.mapOptions.minZoom=minZoom;(minZoom||minZoom===0)&&this.map.setMinZoom(minZoom);}}/** * @function WebMapViewModel.prototype.setMaxZoom * @description 设置地图的最大级别。 * @param {Number} maxZoom - 地图最大级别。 */},{key:"setMaxZoom",value:function setMaxZoom(maxZoom){if(this.map){this.mapOptions.maxZoom=maxZoom;(maxZoom||maxZoom===0)&&this.map.setMinZoom(maxZoom);}}/** * @function WebMapViewModel.prototype.setRenderWorldCopies * @description 设置地图的平铺。 * @param {Boolean} renderWorldCopies - 地图是否平铺。 */},{key:"setRenderWorldCopies",value:function setRenderWorldCopies(renderWorldCopies){if(this.map){this.mapOptions.renderWorldCopies=renderWorldCopies;renderWorldCopies&&this.map.setRenderWorldCopies(renderWorldCopies);}}/** * @function WebMapViewModel.prototype.setBearing * @description 设置地图的方位。 * @param {Number} bearing - 地图的初始方位。 */},{key:"setBearing",value:function setBearing(bearing){if(this.map){this.mapOptions.bearing=bearing;(bearing||bearing===0)&&this.map.setBearing(bearing);}}/** * @function WebMapViewModel.prototype.setPitch * @description 设置地图的俯仰。 * @param {Number} pitch - 地图的初始俯仰。 */},{key:"setPitch",value:function setPitch(pitch){if(this.map){this.mapOptions.pitch=pitch;(pitch||pitch===0)&&this.map.setPitch(pitch);}}},{key:"addSprites",value:function addSprites(sourceId,sprite){var _this$map;if((_this$map=this.map)!==null&&_this$map!==void 0&&_this$map.style){this.map.style.addSprite(sourceId,sprite);}}},{key:"addGlyphs",value:function addGlyphs(sourceId,glyph){var _this$map2;if((_this$map2=this.map)!==null&&_this$map2!==void 0&&_this$map2.style){this.map.style.addGlyphs(sourceId,glyph);}}/** * @function MapViewModel.prototype.changeLayersOrder * @description 设置图层顺序 * @param {string[]} newLayerIds - 正确顺序的图层id数据 */},{key:"changeLayersOrder",value:function changeLayersOrder(newLayerIds){// 最后一个图层的位置不变,从倒数第二个图层开始移动图层顺序 for(var index=newLayerIds.length-2;index>-1;index--){var moveId=newLayerIds[index];var beforeId=newLayerIds[index+1];this.map.moveLayer(moveId,beforeId);}}}]);return MapViewModal;}(_mapboxGlEnhance.default.Evented);var _default=MapViewModal;exports["default"]=_default; /***/ }), /***/ 1406: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var _interopRequireDefault=(__webpack_require__(4836)["default"]);Object.defineProperty(exports, "__esModule", ({value:true}));exports["default"]=void 0;var _objectWithoutProperties2=_interopRequireDefault(__webpack_require__(4925));var _classCallCheck2=_interopRequireDefault(__webpack_require__(5671));var _createClass2=_interopRequireDefault(__webpack_require__(3144));var _inherits2=_interopRequireDefault(__webpack_require__(9340));var _createSuper2=_interopRequireDefault(__webpack_require__(8557));var _compose2=_interopRequireDefault(__webpack_require__(8808));var _react=_interopRequireDefault(__webpack_require__(3899));var _mapGetter=_interopRequireDefault(__webpack_require__(9635));var _excluded=["id","mapNotLoadedTip"];var _dec,_class;var Source=(_dec=(0,_compose2.default)(_mapGetter.default),_dec(_class=/*#__PURE__*/function(_React$PureComponent){(0,_inherits2.default)(Source,_React$PureComponent);var _super=(0,_createSuper2.default)(Source);function Source(props){var _this;(0,_classCallCheck2.default)(this,Source);_this=_super.call(this,props);_this._map=null;return _this;}(0,_createClass2.default)(Source,[{key:"componentWillUnmount",value:function componentWillUnmount(){var _this2=this;setTimeout(function(){_this2._map.removeSource(_this2.props.id);},100);}},{key:"loaded",value:function loaded(map){this._map=map;var _this$props=this.props,id=_this$props.id,mapNotLoadedTip=_this$props.mapNotLoadedTip,sourceOption=(0,_objectWithoutProperties2.default)(_this$props,_excluded);if(this._map.getSource(id)){return;}this._map.addSource(id,sourceOption);}},{key:"render",value:function render(){return null;}}]);return Source;}(_react.default.PureComponent))||_class);exports["default"]=Source; /***/ }), /***/ 8383: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var _interopRequireDefault=(__webpack_require__(4836)["default"]);Object.defineProperty(exports, "__esModule", ({value:true}));exports["default"]=void 0;var _classCallCheck2=_interopRequireDefault(__webpack_require__(5671));var _createClass2=_interopRequireDefault(__webpack_require__(3144));var _SourceModel=_interopRequireDefault(__webpack_require__(7591));var _LayerModel=_interopRequireDefault(__webpack_require__(1016));var SourceListModel=/*#__PURE__*/function(){function SourceListModel(options){(0,_classCallCheck2.default)(this,SourceListModel);this.map=options.map;this.style=this.map.getStyle();this.layers=this.map.getStyle().layers;this.overlayLayers=this.map.overlayLayersManager;this.detailLayers=null;this.sourceList={};this.sourceNames=[];this._initLayers();this._initSource();this.excludeSourceNames=['tdt-search-','tdt-route-','smmeasure','mapbox-gl-draw'];}(0,_createClass2.default)(SourceListModel,[{key:"getSourceList",value:function getSourceList(){var sourceList={};for(var key in this.sourceList){if(key&&this.excludeSource(key)){sourceList[key]=this.sourceList[key];}}return sourceList;}},{key:"getSourceNames",value:function getSourceNames(){var _this=this;var names=[];this.sourceNames.forEach(function(element){if(element&&_this.excludeSource(element)){names.push(element);}});return names;}},{key:"excludeSource",value:function excludeSource(key){for(var i=0;i=0){return false;}}return true;}},{key:"getLegendStyle",value:function getLegendStyle(sourceName){if(sourceName){return this.sourceList[sourceName]?this.sourceList[sourceName].style:'';}var sourceList=Object.values(this.sourceList)||[];var styles=sourceList.filter(function(item){return!!item.style;});return styles;}},{key:"getLayers",value:function getLayers(){return this.detailLayers;}},{key:"getLayersBySourceLayer",value:function getLayersBySourceLayer(sourceName,sourceLayer){return this.sourceList[sourceName]['sourceLayerList'][sourceLayer];}},{key:"getSourceLayersBySource",value:function getSourceLayersBySource(sourceName){return this.sourceList[sourceName]['sourceLayerList'];}},{key:"addSourceStyle",value:function addSourceStyle(sourceName,sourceStyle){if(this.sourceList[sourceName]){this.sourceList[sourceName]['style']=sourceStyle;}}},{key:"_initLayers",value:function _initLayers(){var _this2=this;this.layers&&(this.detailLayers=this.layers.map(function(layer){return _this2.map.getLayer(layer.id);}));var overLayerList=Object.values(this.overlayLayers);overLayerList.forEach(function(overlayer){if(overlayer.id){_this2.detailLayers.push({id:overlayer.id,visibility:overlayer.visibility?'visible':'none',source:overlayer.id});}});}},{key:"_initSource",value:function _initSource(){var _this3=this;this.detailLayers&&this.detailLayers.forEach(function(layer){if(!_this3.sourceList[layer['source']]){_this3.sourceList[layer['source']]=new _SourceModel.default({source:layer['source']});_this3.sourceNames.push(layer['source']);}_this3.sourceList[layer['source']].addLayer(new _LayerModel.default(layer),layer['sourceLayer']);});}}]);return SourceListModel;}();var _default=SourceListModel;exports["default"]=_default; /***/ }), /***/ 7591: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var _interopRequireDefault=(__webpack_require__(4836)["default"]);Object.defineProperty(exports, "__esModule", ({value:true}));exports["default"]=void 0;var _classCallCheck2=_interopRequireDefault(__webpack_require__(5671));var _createClass2=_interopRequireDefault(__webpack_require__(3144));var SourceModel=/*#__PURE__*/function(){function SourceModel(options){(0,_classCallCheck2.default)(this,SourceModel);this.id=options.source;this.sourceLayerList={};this.layers=[];this.type=null;}(0,_createClass2.default)(SourceModel,[{key:"addLayer",value:function addLayer(layer,sourceLayer){if(sourceLayer){if(!this.sourceLayerList[sourceLayer]){this.sourceLayerList[sourceLayer]=[];}this.sourceLayerList[sourceLayer].push(layer);}else{this.sourceLayerList=undefined;}this.layers.push(layer);this.type=layer.type;if([layer.visibility,this.visibility].includes('visible')){this.visibility='visible';}else{this.visibility='none';}}}]);return SourceModel;}();var _default=SourceModel;exports["default"]=_default; /***/ }), /***/ 4416: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var _interopRequireDefault=(__webpack_require__(4836)["default"]);Object.defineProperty(exports, "__esModule", ({value:true}));exports["default"]=void 0;var _objectSpread2=_interopRequireDefault(__webpack_require__(8683));var _classCallCheck2=_interopRequireDefault(__webpack_require__(5671));var _createClass2=_interopRequireDefault(__webpack_require__(3144));var _assertThisInitialized2=_interopRequireDefault(__webpack_require__(7326));var _inherits2=_interopRequireDefault(__webpack_require__(9340));var _createSuper2=_interopRequireDefault(__webpack_require__(8557));var _react=_interopRequireDefault(__webpack_require__(3899));var _resizeDetector=__webpack_require__(1892);var _lodash=_interopRequireDefault(__webpack_require__(1296));var _lodash2=_interopRequireDefault(__webpack_require__(1633));var _lodash3=_interopRequireDefault(__webpack_require__(39));var _antd=__webpack_require__(2721);var _lodash4=_interopRequireDefault(__webpack_require__(9208));var _lodash5=_interopRequireDefault(__webpack_require__(2307));var _mapEvent=_interopRequireDefault(__webpack_require__(1104));var _WebMapViewModel=_interopRequireDefault(__webpack_require__(2872));var _util=__webpack_require__(9752);var _interface=__webpack_require__(4831);var _jsxRuntime=__webpack_require__(5893);var WebMap=/*#__PURE__*/function(_React$Component){(0,_inherits2.default)(WebMap,_React$Component);var _super=(0,_createSuper2.default)(WebMap);function WebMap(props){var _this;(0,_classCallCheck2.default)(this,WebMap);_this=_super.call(this,props);_this._isMounted=false;_this.initializeWebMap=function(){var _this$props=_this.props,target=_this$props.target,serverUrl=_this$props.serverUrl,accessToken=_this$props.accessToken,accessKey=_this$props.accessKey,tiandituKey=_this$props.tiandituKey,withCredentials=_this$props.withCredentials,excludePortalProxyUrl=_this$props.excludePortalProxyUrl,mapOptions=_this$props.mapOptions,autoresize=_this$props.autoresize;_this.viewModel=new _WebMapViewModel.default(_this.props.mapId,{target:target,serverUrl:serverUrl,accessToken:accessToken,accessKey:accessKey,tiandituKey:tiandituKey,withCredentials:withCredentials,excludePortalProxyUrl:excludePortalProxyUrl},mapOptions);if(autoresize){(0,_resizeDetector.addListener)(_this.selfRef.current,_this.__resizeHandler);}};_this.registerEvents=function(){var _this$props2=_this.props,target=_this$props2.target,onLoad=_this$props2.onLoad;_this.viewModel.on('addlayerssucceeded',function(e){if(_this._isMounted){_this.setState({spinning:false});}_mapEvent.default.setMap(target,e.map);_this.viewModel&&_mapEvent.default.setWebMap(target,_this.viewModel);_mapEvent.default.emit('load-map',e.map,target);e.map.resize();_this.map=e.map;// 绑定map event _this.bindMapEvents();/** * @event load * @desc webmap 加载完成之后触发。 * @property {mapboxgl.Map} map - MapBoxGL Map 对象。 */(0,_util.isFunction)(onLoad)&&onLoad((0,_objectSpread2.default)((0,_objectSpread2.default)({},e),{},{component:(0,_assertThisInitialized2.default)(_this)}));});_this.viewModel.on('getmapinfofailed',function(e){var onGetMapFailed=_this.props.onGetMapFailed;/** * @event getMapFailed * @desc 获取 WebMap 地图信息失败。 * @property {Object} error - 失败原因。 */(0,_util.isFunction)(onGetMapFailed)&&onGetMapFailed({error:e.error});_antd.message.error(e.error.message);if(_this._isMounted){_this.setState({spinning:false});}});_this.viewModel.on('getlayerdatasourcefailed',function(e){var onGetLayerDatasourceFailed=_this.props.onGetLayerDatasourceFailed;/** * @event getLayerDatasourceFailed * @desc 获取图层数据失败。 * @property {Object} error - 失败原因。 * @property {Object} layer - 图层信息。 * @property {mapboxgl.Map} map - MapBoxGL Map 对象。 */(0,_util.isFunction)(onGetLayerDatasourceFailed)&&onGetLayerDatasourceFailed({error:e.error,layer:e.layer,map:e.map});// TODO // message.error(this.$t('webmap.getLayerInfoFailed')); _antd.message.error('获取图层信息失败!');});};_this.state={spinning:true,viewModelProps:['mapId','serverUrl','mapOptions.center','mapOptions.zoom','mapOptions.style','mapOptions.crs','mapOptions.minZoom','mapOptions.maxZoom','mapOptions.maxBounds','mapOptions.renderWorldCopies','mapOptions.bearing','mapOptions.pitch','withCredentials']};_this.selfRef=/*#__PURE__*/_react.default.createRef();_this.__resizeHandler=(0,_lodash.default)(_this.__resizeHandler.bind((0,_assertThisInitialized2.default)(_this)),100,{leading:true});return _this;}(0,_createClass2.default)(WebMap,[{key:"componentDidMount",value:function componentDidMount(){this._isMounted=true;this.initializeWebMap();this.registerEvents();}},{key:"componentDidUpdate",value:function componentDidUpdate(prevProps){var _this2=this;this.viewModel&&this.state.viewModelProps.forEach(function(prop){var name=prop.includes('.')?prop.split('.')[1]:prop;var funcName="set".concat((0,_lodash3.default)(name));var propsValue=(0,_lodash4.default)(_this2.props,prop);var prevPropsValue=(0,_lodash4.default)(prevProps,prop);if(propsValue!==undefined&&propsValue!==null&&!(0,_lodash5.default)(propsValue,prevPropsValue)){_this2.viewModel[funcName](propsValue);}});}},{key:"componentWillUnmount",value:function componentWillUnmount(){var _this$props3=this.props,target=_this$props3.target,autoresize=_this$props3.autoresize;_mapEvent.default.deleteMap(target);_mapEvent.default.deleteWebMap(target);if(autoresize&&this.selfRef.current){(0,_resizeDetector.removeListener)(this.selfRef.current,this.__resizeHandler);}this._isMounted=false;}},{key:"__resizeHandler",value:function __resizeHandler(){this.resize();}},{key:"resize",value:function resize(){if(this.viewModel&&this.viewModel.resize){this.viewModel.resize();}}},{key:"bindMapEvents",value:function bindMapEvents(){var _this3=this;Object.keys(this.props).forEach(function(eventName){if(_interface.MAP_EVENT_NAMES.includes(eventName)){var name=eventName.replace('on','');_this3.bindMapEvent(name.toLowerCase(),_this3.mapEventCallback.bind(_this3));}});}},{key:"bindMapEvent",value:function bindMapEvent(eventName,eventCallback){this.map.on(eventName,eventCallback);}},{key:"mapEventCallback",value:function mapEventCallback(event){var data=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};this.emitMapEvent(event.type,(0,_objectSpread2.default)({mapboxEvent:event},data));}},{key:"emitMapEvent",value:function emitMapEvent(name){var data=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};var originEventName="on".concat((0,_lodash2.default)(name));if((0,_util.isFunction)(this.props[originEventName])){this.props[originEventName]((0,_objectSpread2.default)({map:this.map,component:this},data));}}},{key:"render",value:function render(){var spinning=this.state.spinning;var _this$props4=this.props,target=_this$props4.target,children=_this$props4.children;return/*#__PURE__*/(0,_jsxRuntime.jsxs)("div",{id:target,className:"sm-component-web-map",ref:this.selfRef,children:[children,spinning&&/*#__PURE__*/(0,_jsxRuntime.jsx)(_antd.Spin,{size:"large",tip:"\u5730\u56FE\u52A0\u8F7D\u4E2D...",spinning:spinning})]});}}]);return WebMap;}(_react.default.Component);WebMap.defaultProps={target:'map',autoresize:true};var _default=WebMap;exports["default"]=_default; /***/ }), /***/ 2872: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var _interopRequireWildcard=(__webpack_require__(5263)["default"]);var _interopRequireDefault=(__webpack_require__(4836)["default"]);Object.defineProperty(exports, "__esModule", ({value:true}));exports["default"]=void 0;var _classCallCheck2=_interopRequireDefault(__webpack_require__(5671));var _createClass2=_interopRequireDefault(__webpack_require__(3144));var _inherits2=_interopRequireDefault(__webpack_require__(9340));var _createSuper2=_interopRequireDefault(__webpack_require__(8557));var _mapboxGlEnhance=_interopRequireDefault(__webpack_require__(375));var _SourceListModel=_interopRequireDefault(__webpack_require__(8383));var _geometryUtil=__webpack_require__(3595);var _util=__webpack_require__(9752);__webpack_require__(2395);__webpack_require__(8399);__webpack_require__(8553);var convert=_interopRequireWildcard(__webpack_require__(7888));var _canvg=_interopRequireDefault(__webpack_require__(5973));var _echarts=_interopRequireDefault(__webpack_require__(550));var _EchartsLayer=_interopRequireDefault(__webpack_require__(3094));var _ProvinceCenter=_interopRequireDefault(__webpack_require__(5385));var _MunicipalCenter=_interopRequireDefault(__webpack_require__(2158));var _lodash=_interopRequireDefault(__webpack_require__(4461));var _lodash2=_interopRequireDefault(__webpack_require__(3465));/* eslint-disable */ /* Copyright© 2000 - 2023 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html. */ // eslint-disable-line import/extensions // eslint-disable-line import/extensions var MB_SCALEDENOMINATOR_3857=['559082264.0287178','279541132.0143589','139770566.0071794','69885283.00358972','34942641.50179486','17471320.75089743','8735660.375448715','4367830.1877224357','2183915.093862179','1091957.546931089','545978.7734655447','272989.7734655447','272989.3867327723','136494.6933663862','68247.34668319309','34123.67334159654','17061.83667079827','8530.918335399136','4265.459167699568','2132.729583849784'];var MB_SCALEDENOMINATOR_4326=['5.590822640287176E8','2.795411320143588E8','1.397705660071794E8','6.98852830035897E7','3.494264150179485E7','1.7471320750897426E7','8735660.375448713','4367830.187724357','2183915.0938621783','1091957.5469310891','545978.7734655446','272989.3867327723','136494.69336638614','68247.34668319307','34123.673341596535','17061.836670798268','8530.918335399134'];var DEFAULT_WELLKNOWNSCALESET=['GoogleCRS84Quad','GoogleMapsCompatible','GlobalCRS84Scale'];// 迁徙图最大支持要素数量 var MAX_MIGRATION_ANIMATION_COUNT=1000;/** * @class WebMapViewModel * @category ViewModel * @classdesc 对接 iPortal/Online 地图类。目前支持地图坐标系包括:'EPSG:3857','EPSG:4326','EPSG:4490','EPSG:4214','EPSG:4610'。 * @param {number} id - iPortal|Online 地图 ID。 * @param {Object} options - 参数。 * @param {string} [options.target='map'] - 地图容器 ID。 * @param {string} [options.serverUrl="http://www.supermapol.com"] - SuperMap iPortal/Online 服务器地址。当设置 `id` 时有效。 * @param {string} [options.accessToken] - 用于访问 SuperMap iPortal 、SuperMap Online 中受保护的服务。当设置 `id` 时有效。 * @param {string} [options.accessKey] - SuperMap iServer 提供的一种基于 Token(令牌)的用户身份验证机制。当设置 `id` 时有效。 * @param {String} [options.tiandituKey] - 用于访问天地图的服务。当设置 `id` 时有效。 * @param {boolean} [options.withCredentials=false] - 请求是否携带 cookie。当设置 `id` 时有效。 * @param {boolean} [options.excludePortalProxyUrl] - server 传递过来的 URL 是否带有代理。当设置 `id` 时有效。 * @fires WebMapViewModel#mapinitialized * @fires WebMapViewModel#getmapinfofailed * @fires WebMapViewModel#getwmtsinfofailed * @fires WebMapViewModel#getlayerdatasourcefailed * @fires WebMapViewModel#addlayerssucceeded */var WebMapViewModel=/*#__PURE__*/function(_mapboxgl$Evented){(0,_inherits2.default)(WebMapViewModel,_mapboxgl$Evented);var _super=(0,_createSuper2.default)(WebMapViewModel);function WebMapViewModel(id){var _this;var options=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};var mapOptions=arguments.length>2&&arguments[2]!==undefined?arguments[2]:{style:{version:8,sources:{},layers:[]}};(0,_classCallCheck2.default)(this,WebMapViewModel);_this=_super.call(this);_this.mapParams={};// on: any; // fire: any; _this.echartslayer=[];_this.canvgsV=[];_this._layers=[];_this.mapId=id;_this.mapOptions=Object.assign({style:{version:8,sources:{},layers:[]}},mapOptions);_this.serverUrl=options.serverUrl||'http://www.supermapol.com';_this.accessToken=options.accessToken;_this.accessKey=options.accessKey;_this.tiandituKey=options.tiandituKey||'';_this.withCredentials=options.withCredentials||false;_this.target=options.target||'map';_this.excludePortalProxyUrl=options.excludePortalProxyUrl;_this.center=mapOptions.center||[];_this.zoom=mapOptions.zoom;_this.echartslayer=[];_this._createWebMap();_this.on('mapinitialized',function(){_this.map.on('remove',function(){_this._stopCanvg();});});return _this;}/** * @function WebMapViewModel.prototype.resize * @description Map 更新大小。 */(0,_createClass2.default)(WebMapViewModel,[{key:"resize",value:function resize(){this.map&&this.map.resize();this.echartsLayerResize();}/** * @function WebMapViewModel.prototype.EchartsLayerResize * @description echartslayer 更新大小。 */},{key:"echartsLayerResize",value:function echartsLayerResize(){this.echartslayer.forEach(function(echartslayer){echartslayer.chart.resize();});}/** * @function WebMapViewModel.prototype.setMapId * @description 设置地图 ID。 * @param {String} mapId - iPortal|Online 地图 ID。 */},{key:"setMapId",value:function setMapId(mapId){var _this2=this;this.mapId=mapId;setTimeout(function(){_this2._createWebMap();//@ts-ignore window.map=_this2.map;},0);}/** * @function WebMapViewModel.prototype.setServerUrl * @description 设置地图的地址。 * @param {string} options.serverUrl - 地图的地址。 */},{key:"setServerUrl",value:function setServerUrl(serverUrl){this.serverUrl=serverUrl;}},{key:"setWithCredentials",value:function setWithCredentials(withCredentials){this.withCredentials=withCredentials;}/** * @function WebMapViewModel.prototype.setCRS * @description 设置地图的投影。 * @param {Number} crs - 地图投影。 */},{key:"setCrs",value:function setCrs(crs){if(this.map){this.mapOptions.crs=crs;//@ts-ignore crs&&this.map.setCRS(_mapboxGlEnhance.default.CRS.get(crs));}}/** * @function WebMapViewModel.prototype.setZoom * @description 设置地图的缩放级别。 * @param {Number} zoom - 地图缩放级别。 */},{key:"setZoom",value:function setZoom(zoom){if(this.map){this.mapOptions.zoom=zoom;(zoom||zoom===0)&&this.map.setZoom(zoom);}}/** * @function WebMapViewModel.prototype.setCenter * @description 设置地图的中心点。 * @param {Array} center - 地图中心点。 */},{key:"setCenter",value:function setCenter(center){if(this.map){this.mapOptions.center=center;center&¢er.length>0&&this.map.setCenter(center);}}/** * @function WebMapViewModel.prototype.setMaxBounds * @description 设置地图的最大范围。 * @param {Array} maxBounds - 地图最大范围。 */},{key:"setMaxBounds",value:function setMaxBounds(maxBounds){if(this.map){this.mapOptions.maxBounds=maxBounds;maxBounds&&maxBounds.length>0&&this.map.setMaxBounds(maxBounds);}}/** * @function WebMapViewModel.prototype.setMinZoom * @description 设置地图的最小级别。 * @param {Number} minZoom - 地图最小级别。 */},{key:"setMinZoom",value:function setMinZoom(minZoom){if(this.map){this.mapOptions.minZoom=minZoom;(minZoom||minZoom===0)&&this.map.setMinZoom(minZoom);}}/** * @function WebMapViewModel.prototype.setMaxZoom * @description 设置地图的最大级别。 * @param {Number} maxZoom - 地图最大级别。 */},{key:"setMaxZoom",value:function setMaxZoom(maxZoom){if(this.map){this.mapOptions.maxZoom=maxZoom;(maxZoom||maxZoom===0)&&this.map.setMaxZoom(maxZoom);}}/** * @function WebMapViewModel.prototype.setRenderWorldCopies * @description 设置地图的平铺。 * @param {Boolean} renderWorldCopies - 地图是否平铺。 */},{key:"setRenderWorldCopies",value:function setRenderWorldCopies(renderWorldCopies){if(this.map){this.mapOptions.renderWorldCopies=renderWorldCopies;renderWorldCopies&&this.map.setRenderWorldCopies(renderWorldCopies);}}/** * @function WebMapViewModel.prototype.setBearing * @description 设置地图的方位。 * @param {Number} bearing - 地图的初始方位。 */},{key:"setBearing",value:function setBearing(bearing){if(this.map){this.mapOptions.bearing=bearing;(bearing||bearing===0)&&this.map.setBearing(bearing);}}/** * @function WebMapViewModel.prototype.setPitch * @description 设置地图的俯仰。 * @param {Number} pitch - 地图的初始俯仰。 */},{key:"setPitch",value:function setPitch(pitch){if(this.map){this.mapOptions.pitch=pitch;(pitch||pitch===0)&&this.map.setPitch(pitch);}}/** * @function WebMapViewModel.prototype.setStyle * @description 设置地图的样式。 * @param {Object} style - 地图的样式。 */},{key:"setStyle",value:function setStyle(style){if(this.map){this.mapOptions.style=style;style&&this.map.setStyle(style);}}},{key:"getSourceListModel",get:function get(){return this._sourceListModel;}/** * @private * @function WebMapViewModel.prototype._createWebMap * @description 登陆窗口后添加地图图层。 */},{key:"_createWebMap",value:function _createWebMap(){var _this3=this;if(this.map){this.map.remove();this.center=[];this.zoom=null;this._dataflowService&&this._dataflowService.off('messageSucceeded',this._handleDataflowFeaturesCallback);}if(!this.mapId||!this.serverUrl){this.mapOptions.container=this.target;setTimeout(function(){_this3.map=new _mapboxGlEnhance.default.Map(_this3.mapOptions);_this3.map.on('load',function(){_this3.fire('addlayerssucceeded',{map:_this3.map,mapparams:{},layers:[]});});},0);return;}this._legendList={};this._taskID=new Date();var urlArr=this.serverUrl.split('');if(urlArr[urlArr.length-1]!=='/'){this.serverUrl+='/';}var mapUrl=this.serverUrl+'web/maps/'+this.mapId+'/map';if(this.accessToken||this.accessKey){mapUrl+='?'+(this.accessToken&&!this.accessKey)?'token='+this.accessToken:0;}var filter='getUrlResource.json?url=';if(this.excludePortalProxyUrl&&this.serverUrl.indexOf(filter)>-1){// 大屏需求,或者有加上代理的 var urlArray=this.serverUrl.split(filter);if(urlArray.length>1){mapUrl=urlArray[0]+filter+this.serverUrl+'web/maps/'+this.mapId+'/map.json';}}this._getMapInfo(mapUrl,this._taskID);}/** * @private * @function WebMapViewModel.prototype._createMap * @description 创建地图。 */},{key:"_createMap",value:function _createMap(mapInfo){// 获取字体样式 var fonts=[];var layers=mapInfo.layers;// 获取 label 图层字体类型 if(layers&&layers.length>0){layers.forEach(function(layer){layer.labelStyle&&fonts.push(layer.labelStyle.fontFamily);},this);}fonts.push("'supermapol-icons'");var fontFamilys=fonts.join(',');// zoom var center;center=mapInfo.center&&[mapInfo.center.x,mapInfo.center.y];// center var zoom=mapInfo.level||0;zoom=zoom===0?0:zoom-1;if(!center){center=[0,0];}if(this.baseProjection==='EPSG:3857'){center=this._unproject(center);}center=new _mapboxGlEnhance.default.LngLat(center[0],center[1]);// 初始化 map this.map=new _mapboxGlEnhance.default.Map({container:this.target,center:this.center.length?this.center:center,zoom:this.zoom||zoom,style:{version:8,sources:{},// "glyphs": 'http://iclsvr.supermap.io/iserver/services/map-beijing/rest/maps/beijingMap/tileFeature/sdffonts/{fontstack}/{range}.pbf', layers:[]},// @ts-ignore -------- crs 为 enhance 新加属性 crs:this.baseProjection,localIdeographFontFamily:fontFamilys||'',renderWorldCopies:false,preserveDrawingBuffer:this.mapOptions.preserveDrawingBuffer||false});/** * @event WebMapViewModel#mapinitialized * @description Map 初始化成功。 * @property {mapboxglTypes.Map} map - MapBoxGL Map 对象。 */this.fire('mapinitialized',{map:this.map});}/** * @private * @function WebMapViewModel.prototype._getMapInfo * @description 获取地图的 JSON 信息。 * @param {string} url - 请求地图的 url。 */},{key:"_getMapInfo",value:function _getMapInfo(url,_taskID){var _this4=this;var mapUrl=url.indexOf('.json')===-1?"".concat(url,".json"):url;SuperMap.FetchRequest.get(mapUrl,null,{withCredentials:this.withCredentials}).then(function(response){return response.json();}).then(function(mapInfo){_this4.baseProjection=mapInfo.projection;// 存储地图的名称以及描述等信息,返回给用户 _this4.mapParams={title:mapInfo.title,description:mapInfo.description};// 坐标系异常处理 if(_mapboxGlEnhance.default.CRS.get(_this4.baseProjection)){_this4._createMap(mapInfo);var layers=mapInfo.layers;_this4.map.on('load',function(){if(mapInfo.baseLayer&&mapInfo.baseLayer.layerType==='MAPBOXSTYLE'){// 添加矢量瓦片服务作为底图 _this4._addMVTBaseMap(mapInfo);}else{_this4._addBaseMap(mapInfo);}if(!layers||layers.length===0){_this4._sendMapToUser(0,0);}else{_this4._addLayers(layers,_taskID);}});}else{throw Error('不支持当前地图的坐标系');}}).catch(function(error){/** * @event WebMapViewModel#getmapinfofailed * @description 获取地图信息失败。 * @property {Object} error - 失败原因。 */_this4.fire('getmapinfofailed',{error:error});});}},{key:"_addMVTBaseMap",value:function _addMVTBaseMap(mapInfo){var baseLayer=mapInfo.baseLayer,url=baseLayer.dataSource.url;// @ts-ignore this.map.addStyle(url);}/** * @private * @function WebMapViewModel.prototype._addBaseMap * @description 添加底图。 * @param {Object} mapInfo - map 信息。 */},{key:"_addBaseMap",value:function _addBaseMap(mapInfo){this._createBaseLayer(mapInfo);}/** * @private * @function WebMapViewModel.prototype._createBaseLayer * @description 创建底图。 * @param {Object} mapInfo - map 信息。 */},{key:"_createBaseLayer",value:function _createBaseLayer(mapInfo){var layerInfo=mapInfo.baseLayer||mapInfo;var layerType=layerInfo.layerType;// 底图和rest地图兼容 if(layerType.indexOf('TIANDITU_VEC')>-1||layerType.indexOf('TIANDITU_IMG')>-1||layerType.indexOf('TIANDITU_TER')>-1){layerType=layerType.substr(0,12);}var mapUrls={CLOUD:'http://t2.dituhui.com/FileService/image?map=quanguo&type=web&x={x}&y={y}&z={z}',CLOUD_BLACK:'http://t3.dituhui.com/MapService/getGdp?x={x}&y={y}&z={z}',OSM:'http://{a-c}.tile.openstreetmap.org/{z}/{x}/{y}.png',GOOGLE:'http://www.google.cn/maps/vt/pb=!1m4!1m3!1i{z}!2i{x}!3i{y}!2m3!1e0!2sm!3i380072576!3m8!2szh-CN!3scn!5e1105!12m4!1e68!2m2!1sset!2sRoadmap!4e0!5m1!1e0',GOOGLE_CN:'https://mt{0-3}.google.cn/vt/lyrs=m&hl=zh-CN&gl=cn&x={x}&y={y}&z={z}',JAPAN_STD:'http://cyberjapandata.gsi.go.jp/xyz/std/{z}/{x}/{y}.png',JAPAN_PALE:'http://cyberjapandata.gsi.go.jp/xyz/pale/{z}/{x}/{y}.png',JAPAN_RELIEF:'http://cyberjapandata.gsi.go.jp/xyz/relief/{z}/{x}/{y}.png',JAPAN_ORT:'http://cyberjapandata.gsi.go.jp/xyz/ort/{z}/{x}/{y}.jpg'};var url;switch(layerType){case'TIANDITU_VEC':case'TIANDITU_IMG':case'TIANDITU_TER':this._createTiandituLayer(mapInfo);break;case'BING':this._createBingLayer(layerInfo.name);break;case'WMS':this._createWMSLayer(layerInfo);break;case'WMTS':this._createWMTSLayer(layerInfo);break;case'TILE':case'SUPERMAP_REST':this._createDynamicTiledLayer(layerInfo);break;case'CLOUD':case'CLOUD_BLACK':case'OSM':case'JAPAN_ORT':case'JAPAN_RELIEF':case'JAPAN_PALE':case'JAPAN_STD':case'GOOGLE_CN':case'GOOGLE':url=mapUrls[layerType];this._createXYZLayer(layerInfo,url);break;default:break;}}/** * @private * @function WebMapViewModel.prototype._createTiandituLayer * @description 创建天地图底图。 * @param {Object} mapInfo - map 信息。 */},{key:"_createTiandituLayer",value:function _createTiandituLayer(mapInfo){var tiandituUrls=this._getTiandituUrl(mapInfo);var layerType=mapInfo.baseLayer.layerType;var isLabel=Boolean(mapInfo.baseLayer.labelLayerVisible);var labelUrl=tiandituUrls['labelUrl'];var tiandituUrl=tiandituUrls['tiandituUrl'];this._addBaselayer(tiandituUrl,'tianditu-layers-'+layerType);isLabel&&this._addBaselayer(labelUrl,'tianditu-label-layers-'+layerType);}/** * @private * @function WebMapViewModel.prototype._createWMTSLayer * @description 创建 WMTS 底图。 * @param {Object} layerInfo - 地图信息。 */},{key:"_createWMTSLayer",value:function _createWMTSLayer(layerInfo){var _this5=this;var wmtsUrl=this._getWMTSUrl(layerInfo);this._filterWMTSIsMatched(layerInfo,function(isMatched,matchMaxZoom){isMatched&&_this5._addBaselayer([wmtsUrl],'wmts-layers'+layerInfo.name,0,matchMaxZoom);});}/** * @private * @function WebMapViewModel.prototype._filterWMTSIsMatched * @description 过滤能够跟mapboxgl匹配的wmts服务。 * @param {Object} mapInfo - map 信息。 * @callback matchedCallback */},{key:"_filterWMTSIsMatched",value:function _filterWMTSIsMatched(mapInfo,matchedCallback){var _this6=this;var isMatched=false;var matchMaxZoom=22;var url=mapInfo.url;var options={withCredentials:false,withoutFormatSuffix:true};SuperMap.FetchRequest.get(url,null,options).then(function(response){return response.text();}).then(function(capabilitiesText){var converts=convert||window.convert;var tileMatrixSet=JSON.parse(converts.xml2json(capabilitiesText,{compact:true,spaces:4})).Capabilities.Contents.TileMatrixSet;for(var i=0;i} 关系型文件一些参数 */},{key:"_checkUploadToRelationship",value:function _checkUploadToRelationship(fileId){return SuperMap.FetchRequest.get("".concat(this.serverUrl,"web/datas/").concat(fileId,"/datasets.json"),null,{withCredentials:this.withCredentials}).then(function(response){return response.json();}).then(function(result){return result;});}/** * @private * @function ol.supermap.WebMap.prototype._getDataService * @description 获取上传的数据信息 * @param {String} fileId - 文件id * @param {String} datasetName 数据服务的数据集名称 * @returns {Promise} 数据的信息 */},{key:"_getDataService",value:function _getDataService(fileId,datasetName){return SuperMap.FetchRequest.get("".concat(this.serverUrl,"web/datas/").concat(fileId,".json"),null,{withCredentials:this.withCredentials}).then(function(response){return response.json();}).then(function(result){result.fileId=fileId;result.datasetName=datasetName;return result;});}/** * @private * @function WebMapViewModel.prototype._getService * @description 获取当前数据发布的服务中的某种类型服务 * @param {Array} services 服务集合 * @param {String} type 服务类型,RESTDATA, RESTMAP * @returns {Object} 服务 */},{key:"_getService",value:function _getService(services,type){var service=services.filter(function(info){return info&&info.serviceType===type;});return service[0];}},{key:"_getServiceInfoFromLayer",value:function _getServiceInfoFromLayer(layerIndex,len,layer,dataItemServices,datasetName,featureType,info){var _this7=this;var isMapService=info?!info.isMvt:layer.layerType==='HOSTED_TILE',isAdded=false;dataItemServices.forEach(function(service,index){if(isAdded){return;}//有服务了,就不需要循环 if(service&&isMapService&&service.serviceType==='RESTMAP'){isAdded=true;//地图服务,判断使用mvt还是tile _this7._getTileLayerInfo(service.address).then(function(restMaps){restMaps.forEach(function(restMapInfo){var bounds=restMapInfo.bounds;layer.layerType='TILE';layer.orginEpsgCode=_this7.baseProjection;layer.units=restMapInfo.coordUnit&&restMapInfo.coordUnit.toLowerCase();layer.extent=[bounds.left,bounds.bottom,bounds.right,bounds.top];layer.visibleScales=restMapInfo.visibleScales;layer.url=restMapInfo.url;layer.sourceType='TILE';_this7._createBaseLayer(layer);_this7.layerAdded++;_this7._sendMapToUser(_this7.layerAdded,len);});});}// TODO 对接 MVT else if(service&&!isMapService&&service.serviceType==='RESTDATA'){if(info&&info.isMvt){_this7._addVectorLayer(info,layer,featureType);_this7.layerAdded++;_this7._sendMapToUser(_this7.layerAdded,len);}else{//数据服务 isAdded=true;//关系型文件发布的数据服务 _this7._getDatasources(service.address).then(function(datasourceName){layer.dataSource.dataSourceName=datasourceName+':'+datasetName;layer.dataSource.url="".concat(service.address,"/data");_this7._getFeatureBySQL(layer.dataSource.url,[layer.dataSource.dataSourceName||layer.name],function(result){var features=_this7._parseGeoJsonData2Feature({allDatas:{features:result.result.features.features},fileCode:layer.projection,featureProjection:_this7.baseProjection});_this7._addLayer(layer,features,layerIndex);_this7.layerAdded++;_this7._sendMapToUser(_this7.layerAdded,len);},function(err){_this7.layerAdded++;_this7._sendMapToUser(_this7.layerAdded,len);_this7.fire('getlayerdatasourcefailed',{error:err,layer:layer,map:_this7.map});});});}}},this);if(!isAdded){//循环完成了,也没有找到合适的服务。有可能服务被删除 this.layerAdded++;this._sendMapToUser(this.layerAdded,len);this.fire('getlayerdatasourcefailed',{error:null,layer:layer,map:this.map});}}/** * @private * @function WebMapViewModel.prototype._getDatasources * @description 获取关系型文件发布的数据服务中数据源的名称 * @param {String} url - 获取数据源信息的url * @returns {Promise} 数据源名称 */},{key:"_getDatasources",value:function _getDatasources(url){return SuperMap.FetchRequest.get("".concat(url,"/data/datasources.json")).then(function(response){return response.json();}).then(function(datasource){var datasourceNames=datasource.datasourceNames;return datasourceNames[0];});}/** * @private * @function WebMapViewModel.prototype._getTileLayerInfo * @description 获取地图服务的信息 * @param {String} url 地图服务的url(没有地图名字) * @returns {Promise} 地图服务信息 */},{key:"_getTileLayerInfo",value:function _getTileLayerInfo(url){var _this8=this;var proxyUrl=this.serverUrl+'apps/viewer/getUrlResource.json?url=';var requestUrl=proxyUrl+encodeURIComponent(url);var epsgCode=this.baseProjection.split('EPSG:')[1];return SuperMap.FetchRequest.get("".concat(requestUrl,"/maps.json"),null,{withCredentials:this.withCredentials}).then(function(response){return response.json();}).then(function(mapInfo){var promises=[];if(mapInfo){mapInfo.forEach(function(info){var promise=SuperMap.FetchRequest.get("".concat(proxyUrl).concat(info.path,".json?prjCoordSys=").concat(JSON.stringify({epsgCode:epsgCode})),null,{withCredentials:_this8.withCredentials}).then(function(response){return response.json();}).then(function(restMapInfo){restMapInfo.url=info.path;return restMapInfo;});promises.push(promise);});}return Promise.all(promises).then(function(allRestMaps){return allRestMaps;});});}/** * @private * @function WebMapViewModel.prototype._addLayers * @description 添加叠加图层。 * @param {Object} mapInfo - 图层信息。 */},{key:"_addLayers",value:function _addLayers(layers,_taskID){var _this9=this;// 存储地图上所有的图层对象 this._layers=layers;var features;this.layerAdded=0;var len=layers.length;if(len>0){layers.forEach(function(layer,index){if(layer.dataSource&&layer.dataSource.serverId||layer.layerType==='MARKER'||layer.layerType==='HOSTED_TILE'){//数据存储到iportal上了 var dataSource=layer.dataSource,serverId=dataSource?dataSource.serverId:layer.serverId;if(!serverId){_this9._addLayer(layer,null,index);_this9.layerAdded++;_this9._sendMapToUser(_this9.layerAdded,len);return;}if(layer.layerType==='MARKER'||dataSource&&(!dataSource.accessType||dataSource.accessType==='DIRECT')){//原来二进制文件 var url="".concat(_this9.serverUrl,"web/datas/").concat(serverId,"/content.json?pageSize=9999999¤tPage=1");if(_this9.accessToken){url="".concat(url,"&").concat(_this9.accessKey,"=").concat(_this9.accessToken);}SuperMap.FetchRequest.get(url,null,{withCredentials:_this9.withCredentials}).then(function(response){return response.json();}).then(function(data){if(_taskID!==_this9._taskID){return;}if(data.succeed===false){//请求失败 _this9.layerAdded++;_this9._sendMapToUser(_this9.layerAdded,len);// -----------------------todo----------------- _this9.fire('getlayerdatasourcefailed',{error:data.error,layer:layer,map:_this9.map});return;}if(data&&data.type){if(data.type==='JSON'||data.type==='GEOJSON'){data.content=JSON.parse(data.content.trim());features=_this9._formatGeoJSON(data.content);}else if(data.type==='EXCEL'||data.type==='CSV'){features=_this9._excelData2Feature(data.content);}_this9._addLayer(layer,features,index);_this9.layerAdded++;_this9._sendMapToUser(_this9.layerAdded,len);}}).catch(function(error){_this9.layerAdded++;_this9._sendMapToUser(_this9.layerAdded,len);_this9.fire('getlayerdatasourcefailed',{error:error,layer:layer,map:_this9.map});});}else{//关系型文件 var isMapService=layer.layerType==='HOSTED_TILE',_serverId=dataSource?dataSource.serverId:layer.serverId;_this9._checkUploadToRelationship(_serverId).then(function(result){if(result&&result.length>0){var datasetName=result[0].name,featureType=result[0].type.toUpperCase();_this9._getDataService(_serverId,datasetName).then(function(data){var dataItemServices=data.dataItemServices;if(dataItemServices.length===0){_this9.layerAdded++;_this9._sendMapToUser(_this9.layerAdded,len);_this9.fire('getlayerdatasourcefailed',{error:null,layer:layer,map:_this9.map});return;}if(isMapService){var dataService=dataItemServices.filter(function(info){return info&&info.serviceType==='RESTDATA';})[0];_this9._isMvt(dataService.address,datasetName).then(function(info){_this9._getServiceInfoFromLayer(index,len,layer,dataItemServices,datasetName,featureType,info);}).catch(function(){//判断失败就走之前逻辑,>数据量用tile _this9._getServiceInfoFromLayer(index,len,layer,dataItemServices,datasetName,featureType);});}else{_this9._getServiceInfoFromLayer(index,len,layer,dataItemServices,datasetName,featureType);}});}else{_this9.layerAdded++;_this9._sendMapToUser(_this9.layerAdded,len);_this9.fire('getlayerdatasourcefailed',{error:null,layer:layer,map:_this9.map});}}).catch(function(error){_this9.layerAdded++;_this9._sendMapToUser(_this9.layerAdded,len);_this9.fire('getlayerdatasourcefailed',{error:error,layer:layer,map:_this9.map});});}}else if(layer.layerType==='SUPERMAP_REST'||layer.layerType==='TILE'||layer.layerType==='WMS'||layer.layerType==='WMTS'){_this9._createBaseLayer(layer);_this9.layerAdded++;_this9._sendMapToUser(_this9.layerAdded,len);}else if(layer.dataSource&&layer.dataSource.type==='REST_DATA'){//从restData获取数据 var _dataSource=layer.dataSource;_this9._getFeatureBySQL(_dataSource.url,[_dataSource.dataSourseName||layer.name],function(result){features=_this9._parseGeoJsonData2Feature({allDatas:{features:result.result.features.features},fileCode:layer.projection,featureProjection:_this9.baseProjection});_this9._addLayer(layer,features,index);_this9.layerAdded++;_this9._sendMapToUser(_this9.layerAdded,len);},function(err){_this9.layerAdded++;_this9._sendMapToUser(_this9.layerAdded,len);_this9.fire('getlayerdatasourcefailed',{error:err,layer:layer,map:_this9.map});});}else if(layer.dataSource&&layer.dataSource.type==='REST_MAP'&&layer.dataSource.url){_this9._queryFeatureBySQL(layer.dataSource.url,layer.dataSource.layerName,function(result){var recordsets=result&&result.result.recordsets;var recordset=recordsets&&recordsets[0];var attributes=recordset.fields;if(recordset&&attributes){var fileterAttrs=[];for(var i in attributes){var value=attributes[i];if(value.indexOf('Sm')!==0||value==='SmID'){fileterAttrs.push(value);}}_this9._getFeatures(fileterAttrs,layer,function(features){_this9._addLayer(layer,features,index);_this9.layerAdded++;_this9._sendMapToUser(_this9.layerAdded,len);},function(err){_this9.layerAdded++;_this9.fire('getlayerdatasourcefailed',{error:err,layer:layer,map:_this9.map});});}},function(err){_this9.fire('getlayerdatasourcefailed',{error:err,layer:layer,map:_this9.map});},'smid=1');}else if(layer.layerType==='DATAFLOW_POINT_TRACK'||layer.layerType==='DATAFLOW_HEAT'){_this9._getDataflowInfo(layer,function(){_this9._addLayer(layer,null,index);_this9.layerAdded++;_this9._sendMapToUser(_this9.layerAdded,len);},function(e){_this9.layerAdded++;// TODO fire faild });}},this);}}/** * @private * @function WebMapViewModel.prototype._getFeatures */},{key:"_getFeatures",value:function _getFeatures(fields,layerInfo,resolve,reject){var _this10=this;var source=layerInfo.dataSource;// 示例数据 var fileCode=layerInfo.projection;this._queryFeatureBySQL(source.url,source.layerName,function(result){var recordsets=result.result.recordsets[0];var features=recordsets.features.features;var featuresObj=_this10._parseGeoJsonData2Feature({allDatas:{features:features},fileCode:fileCode,featureProjection:_this10.baseProjection});resolve(featuresObj);},function(err){reject(err);},null,fields);}/** * @private * @function WebMapViewModel.prototype._addLayer * @description 将单个图层添加到地图上。 * @param layerInfo 某个图层的图层信息 * @param {Array.} features - feature。 */},{key:"_addLayer",value:function _addLayer(layerInfo,features,index){var layerType=layerInfo.layerType;layerInfo.layerID=layerType+'-'+layerInfo.name+'-'+index;layerInfo.visible=layerInfo.visible?'visible':'none';// mbgl 目前不能处理 geojson 复杂面情况 // mbgl isssue https://github.com/mapbox/mapbox-gl-js/issues/7023 if(features&&features[0]&&features[0].geometry.type==='Polygon'){features=(0,_geometryUtil.handleMultyPolygon)(features);}if(layerInfo.style&&layerInfo.filterCondition){// 将 feature 根据过滤条件进行过滤, 分段专题图和单值专题图因为要计算 styleGroup 所以暂时不过滤 if(layerType!=='RANGE'&&layerType!=='UNIQUE'&&layerType!=='RANK_SYMBOL'){features=this._getFiterFeatures(layerInfo.filterCondition,features);}}if(features&&layerInfo.projection&&layerInfo.projection!=='EPSG:4326'){this._transformFeatures(features);}if(layerType==='VECTOR'){if(layerInfo.featureType==='POINT'){if(layerInfo.style.type==='SYMBOL_POINT'){this._createSymbolLayer(layerInfo,features);}else{this._createGraphicLayer(layerInfo,features);}}else{// 线和面 this._createVectorLayer(layerInfo,features);}}else if(layerType==='UNIQUE'){this._createUniqueLayer(layerInfo,features);}else if(layerType==='RANGE'){this._createRangeLayer(layerInfo,features);}else if(layerType==='HEAT'){this._createHeatLayer(layerInfo,features);}else if(layerType==='MARKER'){this._createMarkerLayer(layerInfo,features);}else if(layerInfo.layerType==='MIGRATION'){this._createMigrationLayer(layerInfo,features);}else if(layerInfo.layerType==='RANK_SYMBOL'){this._createRankSymbolLayer(layerInfo,features);}else if(layerInfo.layerType==='DATAFLOW_POINT_TRACK'||layerInfo.layerType==='DATAFLOW_HEAT'){this._createDataflowLayer(layerInfo);}if(layerInfo.labelStyle&&layerInfo.labelStyle.labelField&&layerInfo.layerType!=='DATAFLOW_POINT_TRACK'){// 存在标签专题图 this._addLabelLayer(layerInfo,features);}}},{key:"_createDataflowLayer",value:function _createDataflowLayer(layerInfo){var dataflowService=new _mapboxGlEnhance.default.supermap.DataFlowService(layerInfo.wsUrl).initSubscribe();this._handleDataflowFeaturesCallback=this._handleDataflowFeatures.bind(this,layerInfo);dataflowService.on('messageSucceeded',this._handleDataflowFeaturesCallback);this._dataflowService=dataflowService;}},{key:"_handleDataflowFeatures",value:function _handleDataflowFeatures(layerInfo,e){var features=e.data&&JSON.parse(e.data);// this._transformFeatures([features]); // TODO 坐标系 this.fire('dataflowfeatureupdated',{features:features,identifyField:layerInfo.identifyField,layerID:layerInfo.layerID});if(layerInfo.filterCondition){//过滤条件 var condition=this._replaceFilterCharacter(layerInfo.filterCondition);var sql='select * from json where ('+condition+')';var filterResult=window['jsonsql'].query(sql,{attributes:features&&features.properties});if(filterResult&&filterResult.length>0){this._addDataflowLayer(layerInfo,features);}}else{this._addDataflowLayer(layerInfo,features);}}},{key:"_getDataFlowRotateStyle",value:function _getDataFlowRotateStyle(features,directionField,identifyField){var iconRotateExpression=['match',['get',identifyField]];features.forEach(function(feature){var value;if(directionField!==undefined&&directionField!=='未设置'&&directionField!=='None'){value=feature.properties[directionField];}else{value=0;}if(value>360||value<0){return null;}// @ts-ignore iconRotateExpression.push(feature.properties[identifyField],parseInt(value));});// @ts-ignore iconRotateExpression.push(0);return iconRotateExpression;}},{key:"_addDataflowLayer",value:function _addDataflowLayer(layerInfo,feature){var layerID=layerInfo.layerID;if(layerInfo.layerType==='DATAFLOW_HEAT'){if(!this.map.getSource(layerID)){this._createHeatLayer(layerInfo,[feature]);}else{this._updateDataFlowFeature(layerID,feature,layerInfo);}}else{var layerStyle=layerInfo.pointStyle;layerInfo.style=layerStyle;if(!this.map.getSource(layerID)){var iconRotateExpression=this._getDataFlowRotateStyle(feature?[feature]:[],layerInfo.directionField,layerInfo.identifyField);if(['BASIC_POINT','SVG_POINT','IMAGE_POINT'].includes(layerStyle.type)){this._createGraphicLayer(layerInfo,[feature],null,iconRotateExpression);}else{this._createSymbolLayer(layerInfo,[feature],null,iconRotateExpression);}}else{this._updateDataFlowFeature(layerID,feature,layerInfo,'point');}if(layerInfo.labelStyle&&layerInfo.visible){if(!this.map.getSource(layerID+'label')){this._addLabelLayer(layerInfo,[feature]);}else{this._updateDataFlowFeature(layerID+'label',feature,layerInfo);}}if(layerInfo.lineStyle&&layerInfo.visible){if(!this.map.getSource(layerID+'-line')){var geometry=feature&&feature.geometry.coordinates||[];var lineFeature={type:'Feature',properties:feature&&feature.properties,geometry:{type:'LineString',coordinates:[geometry]}};this._createVectorLayer({style:layerInfo.lineStyle,featureType:'LINE',visible:'visible',layerID:layerID+'-line'},[lineFeature]);}else{this._updateDataFlowFeature(layerID+'-line',feature,layerInfo,'line');}}}}},{key:"_updateDataFlowFeature",value:function _updateDataFlowFeature(sourceID,newFeature,layerInfo,type){var identifyField=layerInfo.identifyField,maxPointCount=layerInfo.maxPointCount,directionField=layerInfo.directionField;// @ts-ignore var features=(0,_lodash2.default)(this.map.getSource(sourceID)._data.features);var has=false;features.map(function(item,index){if(newFeature&&item.properties[identifyField]===newFeature.properties[identifyField]){has=true;if(type==='line'){var coordinates=item.geometry.coordinates;coordinates.push(newFeature.geometry.coordinates);if(maxPointCount&&coordinates.length>maxPointCount){coordinates.splice(0,coordinates.length-maxPointCount);}features[index].geometry.coordinates=coordinates;}else{features[index]=newFeature;}}});if(!has){if(type==='line'){features.push({type:'Feature',properties:newFeature.properties,geometry:{type:'LineString',coordinates:[newFeature.geometry.coordinates]}});}else{features.push(newFeature);}}// @ts-ignore this.map.getSource(sourceID).setData({type:'FeatureCollection',features:features});if(type==='point'){var _type=layerInfo.pointStyle.type;var iconRotateExpression=this._getDataFlowRotateStyle(features,directionField,identifyField);if(['SVG_POINT','IMAGE_POINT'].includes(_type)){this.map.setLayoutProperty(sourceID,'icon-rotate',iconRotateExpression);}else if(_type==='SYMBOL_POINT'){this.map.setLayoutProperty(sourceID,'text-rotate',iconRotateExpression);}}}},{key:"_getDataflowInfo",value:function _getDataflowInfo(layerInfo,success,faild){var url=layerInfo.url,token;var requestUrl="".concat(url,".json");if(layerInfo.credential&&layerInfo.credential.token){token=layerInfo.credential.token;requestUrl+="?token=".concat(token);}SuperMap.FetchRequest.get(requestUrl).then(function(response){return response.json();}).then(function(result){if(result&&result.featureMetaData){layerInfo.featureType=result.featureMetaData.featureType.toUpperCase();layerInfo.dataSource={dataTypes:{}};if(result.featureMetaData.fieldInfos&&result.featureMetaData.fieldInfos.length>0){result.featureMetaData.fieldInfos.forEach(function(data){var name=data.name.trim();if(data.type==='TEXT'){layerInfo.dataSource.dataTypes[name]='STRING';}else if(['DOUBLE','INT','FLOAT','LONG','SHORT'].includes(data.type)){layerInfo.dataSource.dataTypes[name]='NUMBER';}else{layerInfo.dataSource.dataTypes[name]='UNKNOWN';}});}layerInfo.wsUrl=result.urls[0].url;layerInfo.name=result.urls[0].url.split('iserver/services/')[1].split('/dataflow')[0];success();}else{//失败也要到成功会调函数中,否则不会继续执行 faild();}}).catch(function(){faild();});}},{key:"_createMigrationLayer",value:function _createMigrationLayer(layerInfo,features){window['echarts']=_echarts.default;var properties=this._getFeatureProperties(features);var lineData=this._createLinesData(layerInfo,properties);var pointData=this._createPointsData(lineData,layerInfo,properties);var options=this._createOptions(layerInfo,lineData,pointData);var echartslayer=new _EchartsLayer.default(this.map);echartslayer.chart.setOption(options);this.echartslayer.push(echartslayer);}},{key:"_createOptions",value:function _createOptions(layerInfo,lineData,pointData){var series;var lineSeries=this._createLineSeries(layerInfo,lineData);if(pointData&&pointData.length){var pointSeries=this._createPointSeries(layerInfo,pointData);series=lineSeries.concat(pointSeries);}else{series=lineSeries.slice();}var options={GLMap:{roam:true},// geo: { // map: 'GLMap', // label: { // emphasis: { // show: false // } // }, // roam: true, // itemStyle: { // normal: { // areaColor: '#323c48', // borderColor: '#404a59' // }, // emphasis: { // areaColor: '#2a333d' // } // } // }, series:series};return options;}},{key:"_createPointSeries",value:function _createPointSeries(layerInfo,pointData){var lineSetting=layerInfo.lineSetting;var animationSetting=layerInfo.animationSetting;var labelSetting=layerInfo.labelSetting;var pointSeries=[{name:'point-series',coordinateSystem:'GLMap',zlevel:2,label:{normal:{show:labelSetting.show,position:'right',formatter:'{b}',color:labelSetting.color,fontFamily:labelSetting.fontFamily}},itemStyle:{normal:{color:lineSetting.color||labelSetting.color}},data:pointData}];if(animationSetting.show){// 开启动画 // @ts-ignore pointSeries[0].type='effectScatter';// @ts-ignore pointSeries[0].rippleEffect={brushType:'stroke'};}else{// 关闭动画 // @ts-ignore pointSeries[0].type='scatter';}return pointSeries;}},{key:"_createLineSeries",value:function _createLineSeries(layerInfo,lineData){var lineSetting=layerInfo.lineSetting;var animationSetting=layerInfo.animationSetting;var linesSeries=[// 轨迹线样式 {name:'line-series',coordinateSystem:'GLMap',type:'lines',zlevel:1,effect:{show:animationSetting.show,constantSpeed:animationSetting.constantSpeed,trailLength:0,symbol:animationSetting.symbol,symbolSize:animationSetting.symbolSize},lineStyle:{normal:{color:lineSetting.color,type:lineSetting.type,width:lineSetting.width,opacity:lineSetting.opacity,curveness:lineSetting.curveness}},data:lineData}];if(lineData.length>=MAX_MIGRATION_ANIMATION_COUNT){// @ts-ignore linesSeries[0].large=true;// @ts-ignore linesSeries[0].largeThreshold=100;// @ts-ignore linesSeries[0].blendMode='lighter';}return linesSeries;}},{key:"_createLinesData",value:function _createLinesData(layerInfo,properties){var data=[];if(properties&&properties.length){// 重新获取数据 var from=layerInfo.from,to=layerInfo.to,fromCoord,toCoord;if(from.type==='XY_FIELD'&&from['xField']&&from['yField']&&to['xField']&&to['yField']){properties.forEach(function(property){var fromX=property[from['xField']],fromY=property[from['yField']],toX=property[to['xField']],toY=property[to['yField']];if(!fromX||!fromY||!toX||!toY){return;}fromCoord=[property[from['xField']],property[from['yField']]];toCoord=[property[to['xField']],property[to['yField']]];data.push({coords:[fromCoord,toCoord]});});}else if(from.type==='PLACE_FIELD'&&from['field']&&to['field']){var centerDatas=_ProvinceCenter.default.concat(_MunicipalCenter.default);properties.forEach(function(property){var fromField=property[from['field']],toField=property[to['field']];fromCoord=centerDatas.find(function(item){return _mapboxGlEnhance.default.supermap.Util.isMatchAdministrativeName(item.name,fromField);});toCoord=centerDatas.find(function(item){return _mapboxGlEnhance.default.supermap.Util.isMatchAdministrativeName(item.name,toField);});if(!fromCoord||!toCoord){return;}data.push({coords:[fromCoord.coord,toCoord.coord]});});}}return data;}},{key:"_createPointsData",value:function _createPointsData(lineData,layerInfo,properties){var data=[],labelSetting=layerInfo.labelSetting;// 标签隐藏则直接返回 if(!labelSetting.show||!lineData.length){return data;}var fromData=[],toData=[];lineData.forEach(function(item,idx){var coords=item.coords,fromCoord=coords[0],toCoord=coords[1],fromProperty=properties[idx][labelSetting.from],toProperty=properties[idx][labelSetting.to];// 起始字段去重 var f=fromData.find(function(d){return d.value[0]===fromCoord[0]&&d.value[1]===fromCoord[1];});!f&&fromData.push({name:fromProperty,value:fromCoord});// 终点字段去重 var t=toData.find(function(d){return d.value[0]===toCoord[0]&&d.value[1]===toCoord[1];});!t&&toData.push({name:toProperty,value:toCoord});});data=fromData.concat(toData);return data;}},{key:"_createRankSymbolLayer",value:function _createRankSymbolLayer(layerInfo,features){var fieldName=layerInfo.themeSetting.themeField;var style=layerInfo.style;var featureType=layerInfo.featureType;var styleSource=this._createRankStyleSource(layerInfo,features,layerInfo.featureType);var styleGroups=styleSource.styleGroups;features=this._getFiterFeatures(layerInfo.filterCondition,features);// 获取 expression var expression=['match',['get','index']];features.forEach(function(row){var tartget=parseFloat(row.properties[fieldName]);if(styleGroups){for(var i=0;i} features - feature。 */},{key:"_addLabelLayer",value:function _addLabelLayer(layerInfo,features){var labelStyle=layerInfo.labelStyle;this.map.addLayer({id:layerInfo.layerID+'label',type:'symbol',source:{type:'geojson',data:{type:'FeatureCollection',features:features}},paint:{'text-color':labelStyle.fill,'text-halo-color':'rgba(255,255,255,0.8)','text-halo-width':parseFloat(labelStyle.fontSize)||12},layout:{'text-field':"{".concat(labelStyle.labelField,"}"),'text-size':parseFloat(labelStyle.fontSize)||12,'text-offset':labelStyle.offsetX?[labelStyle.offsetX/10||0,labelStyle.offsetY/10||0]:[0,-2.5],'text-font':['DIN Offc Pro Italic','Arial Unicode MS Regular'],visibility:layerInfo.visible}});}/** * @private * @function WebMapViewModel.prototype._createSymbolLayer * @description 添加 symbol 图层。 * @param layerInfo 某个图层的图层信息。 * @param {Array.} features - feature。 */},{key:"_createSymbolLayer",value:function _createSymbolLayer(layerInfo,features,textSize,textRotateExpresion){// 用来请求symbol_point字体文件 var target=document.getElementById("".concat(this.target));target.classList.add('supermapol-icons-map');var style=layerInfo.style;var unicode=layerInfo.style.unicode;var text=String.fromCharCode(parseInt(unicode.replace(/^&#x/,''),16));var layerID=layerInfo.layerID;this.map.addSource(layerID,{type:'geojson',data:{type:'FeatureCollection',features:[]}});this.map.addLayer({id:layerID,type:'symbol',source:layerID,paint:{'text-color':style.fillColor},layout:{'text-field':text,'text-size':textSize||style.fontSize&&parseFloat(style.fontSize)||12,'text-font':['DIN Offc Pro Italic','Arial Unicode MS Regular'],'text-rotate':textRotateExpresion||0,visibility:layerInfo.visible}});// @ts-ignore this.map.getSource(layerID).setData({type:'FeatureCollection',features:features});}/** * @private * @function WebMapViewModel.prototype._createGraphicLayer * @description 创建 Graphic 图层。 * @param {Object} layerInfo - map 信息。 * @param {Array} features - 属性 信息。 */},{key:"_createGraphicLayer",value:function _createGraphicLayer(layerInfo,features,iconSizeExpression,iconRotateExpression){var _this11=this;var style=layerInfo.style;var layerID=layerInfo.layerID;var source={type:'geojson',data:{type:'FeatureCollection',features:features}};if(style.type==='IMAGE_POINT'){var imageInfo=style.imageInfo;this.map.loadImage(imageInfo.url,function(error,image){if(error){console.log(error);}var iconSize=Number.parseFloat((style.radius/image.height).toFixed(2))*2;_this11.map.addImage('imageIcon',image);_this11.map.addLayer({id:layerID,type:'symbol',source:source,layout:{'icon-image':'imageIcon','icon-size':iconSizeExpression||iconSize,visibility:layerInfo.visible,'icon-rotate':iconRotateExpression||0}});});}else if(style.type==='SVG_POINT'){var svgUrl=style.url;if(!this._svgDiv){this._svgDiv=document.createElement('div');document.body.appendChild(this._svgDiv);}this._getCanvasFromSVG(svgUrl,this._svgDiv,function(canvas){var imgUrl=canvas.toDataURL('img/png');imgUrl&&_this11.map.loadImage(imgUrl,function(error,image){if(error){console.log(error);}var iconSize=Number.parseFloat((style.radius/canvas.width).toFixed(2));_this11.map.addImage('imageIcon',image);_this11.map.addLayer({id:layerID,type:'symbol',source:source,layout:{'icon-image':'imageIcon','icon-size':iconSizeExpression||iconSize,visibility:layerInfo.visible,'icon-rotate':iconRotateExpression||0}});});});}else{var layerStyle={style:this._transformStyleToMapBoxGl(style,layerInfo.featureType),layout:{visibility:layerInfo.visible}};this._addOverlayToMap('POINT',source,layerID,layerStyle);}}/** * @private * @function WebMapViewModel.prototype._createUniqueLayer * @description 创建单值图层。 * @param layerInfo 某个图层的图层信息 * @param features 图层上的 feature */},{key:"_createUniqueLayer",value:function _createUniqueLayer(layerInfo,features){var styleGroup=this._getUniqueStyleGroup(layerInfo,features);features=this._getFiterFeatures(layerInfo.filterCondition,features);var style=layerInfo.style;var themeField=layerInfo.themeSetting.themeField;Object.keys(features[0].properties).forEach(function(key){key.toLocaleUpperCase()===themeField.toLocaleUpperCase()&&(themeField=key);});var type=layerInfo.featureType;var expression=['match',['get','index']];var layerID=layerInfo.layerID;features.forEach(function(row){styleGroup.forEach(function(item){if(item.value===row.properties[themeField]){expression.push(row.properties['index'],item.color);}});});expression.push('#ffffff');// 图例相关 this._initLegendConfigInfo(layerInfo,styleGroup);var visible=layerInfo.visible;var layerStyle={style:this._transformStyleToMapBoxGl(style,type,expression),layout:{visibility:visible}};var source={type:'geojson',data:{type:'FeatureCollection',features:features}};this._addOverlayToMap(type,source,layerID,layerStyle);type==='POLYGON'&&style.strokeColor&&this._addStrokeLineForPoly(style,source,layerID+'-strokeLine',visible);}/** * @private * @function WebMapViewModel.prototype._getUniqueStyleGroup * @description 获取单值的目标字段与颜色的对应数组。 * @param layerInfo 某个图层的图层信息 * @param features 图层上的 feature */},{key:"_getUniqueStyleGroup",value:function _getUniqueStyleGroup(parameters,features){// 找出所有的单值 var featureType=parameters.featureType;var style=parameters.style;var themeSetting=parameters.themeSetting;var fieldName=themeSetting.themeField;var colors=themeSetting.colors;Object.keys(features[0].properties).forEach(function(key){key.toLocaleUpperCase()===fieldName.toLocaleUpperCase()&&(fieldName=key);});var names=[];var customSettings=themeSetting.customSettings;for(var i in features){var properties=features[i].properties;var name=properties[fieldName];var isSaved=false;for(var j in names){if(names[j]===name){isSaved=true;break;}}if(!isSaved){names.push(name);}}// 获取一定量的颜色 var curentColors=colors;curentColors=SuperMap.ColorsPickerUtil.getGradientColors(curentColors,names.length);// 生成styleGroup var styleGroup=[];names.forEach(function(name,index){var color=curentColors[index];if(name in customSettings){color=customSettings[name];}if(featureType==='LINE'){style.strokeColor=color;}else{style.fillColor=color;}styleGroup.push({color:color,value:name});},this);return styleGroup;}/** * @private * @function WebMapViewModel.prototype._getWMTSUrl * @description 根据传入的配置信息拼接wmts url。 * @param options 配置对象 */},{key:"_getWMTSUrl",value:function _getWMTSUrl(options){var obj={service:'WMTS',request:'GetTile',version:'1.0.0',style:'default',layer:options.layer,tilematrixSet:options.tileMatrixSet,format:'image/png'};var url=options.url;url+=this._getParamString(obj,url)+'&tilematrix={z}&tilerow={y}&tilecol={x}';return url;}/** * @private * @function WebMapViewModel.prototype._createMarkerLayer * @description 添加标记图层。 * @param {Array.} features - feature。 */},{key:"_createMarkerLayer",value:function _createMarkerLayer(layerInfo,features){var _this12=this;features&&features.forEach(function(feature){var geomType=feature.geometry.type.toUpperCase();var defaultStyle=feature.dv_v5_markerStyle;if(geomType==='POINT'&&defaultStyle.text){// 说明是文字的feature类型 geomType='TEXT';}var featureInfo=_this12._setFeatureInfo(feature);feature.properties['useStyle']=defaultStyle;feature.properties['featureInfo']=featureInfo;if(geomType==='POINT'&&defaultStyle.src&&defaultStyle.src.indexOf('http://')===-1&&defaultStyle.src.indexOf('https://')===-1){// 说明地址不完整 defaultStyle.src=_this12.serverUrl+defaultStyle.src;}var source={type:'geojson',data:feature};var index=feature.properties.index;var layerID=geomType+'-'+index;// image-marker geomType==='POINT'&&defaultStyle.src&&defaultStyle.src.indexOf('svg')<=-1&&_this12.map.loadImage(defaultStyle.src,function(error,image){if(error){console.log(error);}_this12.map.addImage(index+'',image);_this12.map.addLayer({id:layerID,type:'symbol',source:source,layout:{'icon-image':defaultStyle.src,'icon-size':defaultStyle.scale,visibility:layerInfo.visible}});});// svg-marker if(geomType==='POINT'&&defaultStyle.src&&defaultStyle.src.indexOf('svg')>-1){if(!_this12._svgDiv){_this12._svgDiv=document.createElement('div');document.body.appendChild(_this12._svgDiv);}_this12._getCanvasFromSVG(defaultStyle.src,_this12._svgDiv,function(canvas){var imgUrl=canvas.toDataURL('img/png');imgUrl&&_this12.map.loadImage(imgUrl,function(error,image){if(error){console.log(error);}_this12.map.addImage(index+'',image);_this12.map.addLayer({id:layerID,type:'symbol',source:source,layout:{'icon-image':index+'','icon-size':defaultStyle.scale,visibility:layerInfo.visible}});console.log(_this12.map.getStyle());});});}// point-line-polygon-marker if(!defaultStyle.src){var layeStyle={layout:{}};if(geomType==='LINESTRING'&&defaultStyle.lineCap){geomType='LINE';layeStyle.layout={'line-cap':defaultStyle.lineCap};}var visible=layerInfo.visible;layeStyle.layout.visibility=visible;// get style layeStyle.style=_this12._transformStyleToMapBoxGl(defaultStyle,geomType);_this12._addOverlayToMap(geomType,source,layerID,layeStyle);// 若面有边框 geomType==='POLYGON'&&defaultStyle.strokeColor&&_this12._addStrokeLineForPoly(defaultStyle,source,layerID+'-strokeLine',visible);}},this);}/** * @private * @function WebMapViewModel.prototype._setFeatureInfo * @description 设置 feature 信息。 * @param {Array.} features - feature。 */},{key:"_setFeatureInfo",value:function _setFeatureInfo(feature){var featureInfo;var info=feature.dv_v5_markerInfo;if(info&&info.dataViz_title){// 有featureInfo信息就不需要再添加 featureInfo=info;}else{// featureInfo = this.getDefaultAttribute(); return info;}var properties=feature.properties;for(var key in featureInfo){if(properties[key]){featureInfo[key]=properties[key];delete properties[key];}}return featureInfo;}/** * @private * @function WebMapViewModel.prototype._createHeatLayer * @description 添加热力图。 * @param {Array.} features - feature。 */},{key:"_createHeatLayer",value:function _createHeatLayer(layerInfo,features){var style=layerInfo.themeSetting;var layerOption={gradient:style.colors.slice(),radius:parseInt(style.radius)};// 自定义颜色 var customSettings=style.customSettings;for(var i in customSettings){layerOption.gradient[i]=customSettings[i];}// 权重字段恢复 if(style.weight){this._changeWeight(features,style.weight);}var color=['interpolate',['linear'],['heatmap-density']];var length=layerOption.gradient.length;var step=parseFloat((1/length).toFixed(2));layerOption.gradient.forEach(function(item,index){color.push(index*step);if(index===0){item=_mapboxGlEnhance.default.supermap.Util.hexToRgba(item,0);}color.push(item);});// 图例相关 this._initLegendConfigInfo(layerInfo,layerOption.gradient);var paint={'heatmap-color':color,'heatmap-radius':style.radius+15,'heatmap-intensity':{base:1,stops:[[0,0.8],[22,1]]}};if(features[0].weight&&features.length>=4){var weight=[];features.forEach(function(item){weight.push(item.weight);});var max=SuperMap.ArrayStatistic.getMax(weight);var min=SuperMap.ArrayStatistic.getMin(weight);paint['heatmap-weight']=['interpolate',['linear'],['get','weight'],min,0,max,1];}this.map.addLayer({id:layerInfo.layerID,type:'heatmap',source:{type:'geojson',data:{type:'FeatureCollection',features:features}},paint:paint});}/** * @private * @function WebMapViewModel.prototype._changeWeight * @description 改变当前权重字段 * @param {Array.} features - feature。 * @param {String} weightFeild - 权重字段 */},{key:"_changeWeight",value:function _changeWeight(features,weightFeild){this._fieldMaxValue={};this._getMaxValue(features,weightFeild);var maxValue=this._fieldMaxValue[weightFeild];features.forEach(function(feature){var attributes=feature.properties;var value=attributes[weightFeild];feature['weight']=value/maxValue;});}/** * @private * @function WebMapViewModel.prototype._getMaxValue * @description 获取当前字段对应的最大值,用于计算权重。 * @param {Array.} features - feature。 * @param {String} weightFeild - 权重字段 */},{key:"_getMaxValue",value:function _getMaxValue(features,weightField){var values=[];var attributes;var field=weightField;if(this._fieldMaxValue[field]){return;}features.forEach(function(feature){// 收集当前权重字段对应的所有值 attributes=feature.properties;attributes&&parseFloat(attributes[field])&&values.push(parseFloat(attributes[field]));});this._fieldMaxValue[field]=SuperMap.ArrayStatistic.getArrayStatistic(values,'Maximum');}/** * @private * @function WebMapViewModel.prototype._createRangeLayer * @description 添加分段专题图。 * @param {Array.} features - feature。 */},{key:"_createRangeLayer",value:function _createRangeLayer(layerInfo,features){var fieldName=layerInfo.themeSetting.themeField;var style=layerInfo.style;var featureType=layerInfo.featureType;var styleGroups=this._getRangeStyleGroup(layerInfo,features);features=this._getFiterFeatures(layerInfo.filterCondition,features);var source={type:'geojson',data:{type:'FeatureCollection',features:features}};// 获取 expression var expression=['match',['get','index']];features.forEach(function(row){var tartget=parseFloat(row.properties[fieldName]);if(styleGroups){for(var i=0;i0){// afterFilterFeatureIdx.push(i); filterFeatures.push(feature);}}return filterFeatures;}/** * @private * @function WebMapViewModel.prototype._replaceFilterCharacter * @description 获取过滤字符串。 * @param {String} filterString - 过滤条件。 */},{key:"_replaceFilterCharacter",value:function _replaceFilterCharacter(filterString){filterString=filterString.replace(/=/g,'==').replace(/AND|and/g,'&&').replace(/or|OR/g,'||').replace(/<==/g,'<=').replace(/>==/g,'>=');return filterString;}/** * @private * @function WebMapViewModel.prototype._getRangeStyleGroup * @description 获取分段样式。 * @param {Array.} features - feature。 */},{key:"_getRangeStyleGroup",value:function _getRangeStyleGroup(layerInfo,features){// 找出分段值 var featureType=layerInfo.featureType;var style=layerInfo.style;var values=[];var attributes;var themeSetting=layerInfo.themeSetting;var customSettings=themeSetting.customSettings;var fieldName=themeSetting.themeField;var segmentCount=themeSetting.segmentCount;features.forEach(function(feature){attributes=feature.properties||feature.get('Properties');if(attributes){// 过滤掉非数值的数据 attributes[fieldName]&&_mapboxGlEnhance.default.supermap.Util.isNumber(attributes[fieldName])&&values.push(parseFloat(attributes[fieldName]));}else if(feature.get(fieldName)&&_mapboxGlEnhance.default.supermap.Util.isNumber(feature.get(fieldName))){feature.get(fieldName)&&values.push(parseFloat(feature.get(fieldName)));}},this);var segements=SuperMap.ArrayStatistic.getArraySegments(values,themeSetting.segmentMethod,segmentCount);if(segements){var itemNum=segmentCount;if(attributes&&segements[0]===segements[attributes.length-1]){itemNum=1;segements.length=2;}// 保留两位有效数 for(var i=0;i} layers - 地图上所有的图层对象。 */this._sourceListModel=new _SourceListModel.default({map:this.map});for(var layerID in this._legendList){this._sourceListModel.addSourceStyle(layerID,this._legendList[layerID]);}for(var index=this._layers.length-2;index>-1;index--){var targetlayerId=this._layers[index].layerID;var beforLayerId=this._layers[index+1].layerID;this.map.moveLayer(targetlayerId,beforLayerId);}this.fire('addlayerssucceeded',{map:this.map,mapparams:this.mapParams,layers:this._layers});}}/** * @function WebMapViewModel.prototype._unproject * @private * @description 墨卡托转经纬度。 * @param {} point - 待转换的点。 */},{key:"_unproject",value:function _unproject(point){var d=180/Math.PI;var r=6378137;var ts=Math.exp(-point[1]/r);var phi=Math.PI/2-2*Math.atan(ts);for(var i=0,dphi=0.1,con;i<15&&Math.abs(dphi)>1e-7;i++){con=1;dphi=Math.PI/2-2*Math.atan(ts*con)-phi;phi+=dphi;}return[point[0]*d/r,phi*d];}/** * @function WebMapViewModel.prototype._getParamString * @private * @param {Object} obj - 待添加的参数。 * @param {string} existingUrl - 待添加参数的 url。 * @param {Boolean} [uppercase] - 参数是否转换为大写。 */},{key:"_getParamString",value:function _getParamString(obj,existingUrl){var uppercase=arguments.length>2&&arguments[2]!==undefined?arguments[2]:false;var params=[];for(var i in obj){params.push((uppercase?i.toUpperCase():i)+'='+obj[i]);}return(!existingUrl||existingUrl.indexOf('?')===-1?'?':'&')+params.join('&');}/** * @private * @function WebMapViewModel.prototype._transformStyleToMapBoxGl * @description 根据图层类型将 layerInfo 中的 style 属性格式转换为 mapboxglTypes 中的 style 格式。 * @param {Object} style - layerInfo中的style属性 * @param {String} type - 图层类型 * @param {Array} [expression] - 存储颜色值得表达式 */},{key:"_transformStyleToMapBoxGl",value:function _transformStyleToMapBoxGl(style,type,expression,expressionType){var transTable={};if((style.type==='POINT'||style.type==='BASIC_POINT'||type==='POINT')&&type!=='LINE'){transTable={fillColor:'circle-color',strokeWidth:'circle-stroke-width',fillOpacity:'circle-opacity',radius:'circle-radius',strokeColor:'circle-stroke-color',strokeOpacity:'circle-stroke-opacity'};}else if(['LINE','LINESTRING','MULTILINESTRING'].includes(type)){transTable={strokeWidth:'line-width',strokeColor:'line-color',strokeOpacity:'line-opacity'};}else if(['REGION','POLYGON','MULTIPOLYGON'].includes(type)){transTable={fillColor:'fill-color',fillOpacity:'fill-opacity',strokeColor:'fill-outline-color'};}var newObj={};for(var item in style){if(transTable[item]){newObj[transTable[item]]=style[item];}}if(expression){if(expressionType){newObj[expressionType]=expression;}else if(newObj['circle-color']){newObj['circle-color']=expression;}else if(newObj['line-color']){newObj['line-color']=expression;}else{newObj['fill-color']=expression;}}if(style.lineDash&&style.lineDash!=='solid'&&type==='LINE'){newObj['line-dasharray']=this._dashStyle(style);}return newObj;}/** * @private * @function WebMapViewModel.prototype.._dashStyle * @description 符号样式。 * @param {Object} style - 样式参数。 * @param {number} widthFactor - 宽度系数。 */},{key:"_dashStyle",value:function _dashStyle(style){if(!style){return[];}// var w = style.strokeWidth * widthFactor; var w=1;var str=style.strokeDashstyle||style.lineDash;switch(str){case'solid':return[];case'dot':return[1,4*w];case'dash':return[4*w,4*w];case'dashdot':return[4*w,4*w,1*w,4*w];case'longdash':return[8*w,4*w];case'longdashdot':return[8*w,4*w,1,4*w];default:if(!str){return[];}if(SuperMap.Util.isArray(str)){return str;}str=SuperMap.String.trim(str).replace(/\s+/g,',');return str.replace(/\[|\]/gi,'').split(',');}}/** * @private * @description 将SVG转换成Canvas * @param svgUrl * @param divDom * @param callBack */},{key:"_getCanvasFromSVG",value:function _getCanvasFromSVG(svgUrl,divDom,callBack){var _this13=this;// 一个图层对应一个canvas var canvas=document.createElement('canvas');canvas.id='dataviz-canvas-'+_mapboxGlEnhance.default.supermap.Util.newGuid(8);canvas.style.display='none';divDom.appendChild(canvas);var canvgs=window.canvg&&window.canvg.default?window.canvg.default:_canvg.default;try{var ctx=canvas.getContext('2d');canvgs.from(ctx,svgUrl,{ignoreMouse:true,ignoreAnimation:true,forceRedraw:function forceRedraw(){return false;}}).then(function(v){v.start();_this13.canvgsV.push(v);if(canvas.width>300||canvas.height>300){return;}callBack(canvas);});}catch(error){console.log(error);}}},{key:"_stopCanvg",value:function _stopCanvg(){this.canvgsV.forEach(function(v){return v.stop();});this.canvgsV=[];}/** * @private * @function WebMapViewModel.prototype._addOverlayToMap * @description 添加基础矢量图层到 MAP * @param {Object} style - mabgl style * @param {String} type - 图层类型 */},{key:"_addOverlayToMap",value:function _addOverlayToMap(type,source,layerID,layerStyle){var mbglTypeMap={POINT:'circle',LINE:'line',POLYGON:'fill'};var mbglType=mbglTypeMap[type];if(mbglType==='circle'||mbglType==='line'||mbglType==='fill'){this.map.addLayer({id:layerID,type:mbglType,source:source,paint:layerStyle.style,layout:layerStyle.layout||{}});}}},{key:"_addBaselayer",value:function _addBaselayer(url,layerID){var minzoom=arguments.length>2&&arguments[2]!==undefined?arguments[2]:0;var maxzoom=arguments.length>3&&arguments[3]!==undefined?arguments[3]:22;var source={type:'raster',tiles:url,tileSize:256};this.map.addLayer({id:layerID,type:'raster',source:source,minzoom:minzoom,maxzoom:maxzoom});}/** * @private * @function WebMapViewModel.prototype._addStrokeLineForPoly * @description 添加面的边框。 * @param {Object} style - mabgl style */},{key:"_addStrokeLineForPoly",value:function _addStrokeLineForPoly(style,source,layerID,visible){var lineStyle={style:this._transformStyleToMapBoxGl(style,'LINE'),layout:{visibility:visible}};this._addOverlayToMap('LINE',source,layerID,lineStyle);}/** * @private * @function WebMapViewModel.prototype._parseGeoJsonData2Feature * @description 将从restData地址上获取的json转换成feature(从iserver中获取的json转换成feature) * @param {object} metaData - json内容 */},{key:"_parseGeoJsonData2Feature",value:function _parseGeoJsonData2Feature(metaData){var allFeatures=metaData.allDatas.features;var features=[];for(var i=0,len=allFeatures.length;i 0'});getFeatureBySQLParams=new SuperMap.GetFeaturesBySQLParameters({queryParameter:getFeatureParam,datasetNames:datasetNames,fromIndex:0,toIndex:-1,maxFeatures:-1,returnContent:true});var options={eventListeners:{processCompleted:function processCompleted(getFeaturesEventArgs){_processCompleted&&_processCompleted(getFeaturesEventArgs);},processFailed:function processFailed(e){processFaild&&processFaild(e);}}};getFeatureBySQLService=new SuperMap.GetFeaturesBySQLService(url,options);getFeatureBySQLService.processAsync(getFeatureBySQLParams);}/** * @private * @function WebMapViewModel.prototype._queryFeatureBySQL * @description 通过 sql 方式查询数据。 */},{key:"_queryFeatureBySQL",value:function _queryFeatureBySQL(url,layerName,processCompleted,processFaild,attributeFilter,fields,epsgCode,startRecord,recordLength,onlyAttribute){var queryParam=new SuperMap.FilterParameter({name:layerName,attributeFilter:attributeFilter});if(fields){queryParam.fields=fields;}var params={queryParams:[queryParam]};if(onlyAttribute){params.queryOption=SuperMap.QueryOption.ATTRIBUTE;}startRecord&&(params.startRecord=startRecord);recordLength&&(params.expectCount=recordLength);if(epsgCode){params.prjCoordSys={epsgCode:epsgCode};}var queryBySQLParams=new SuperMap.QueryBySQLParameters(params);var queryBySQLService=new _mapboxGlEnhance.default.supermap.QueryService(url);queryBySQLService.queryBySQL(queryBySQLParams,function(data){data.type==='processCompleted'?processCompleted(data):processFaild(data);});}},{key:"_initLegendConfigInfo",value:function _initLegendConfigInfo(layerInfo,style){if(!this._legendList[layerInfo.layerID]){this._legendList[layerInfo.layerID]={layerType:layerInfo.layerType,featureType:layerInfo.featureType,layerId:layerInfo.layerID,themeField:layerInfo.layerType==='HEAT'?layerInfo.themeSetting.weight:layerInfo.themeSetting.themeField,styleGroup:style};}}},{key:"_getFeatureProperties",value:function _getFeatureProperties(features){var properties=[];if(features&&features.length){features.forEach(function(feature){var property=feature.properties;property&&properties.push(property);});}return properties;}},{key:"_addVectorLayer",value:function _addVectorLayer(info,layerInfo,featureType){var style=this._getDataVectorTileStyle(featureType);var paint=this._transformStyleToMapBoxGl(style,featureType);var url=info.url+'/tileFeature.mvt';var origin=_mapboxGlEnhance.default.CRS.get(this.baseProjection).getOrigin();url+="?&returnAttributes=true&width=512&height=512&x={x}&y={y}&scale={scale}&origin={x:".concat(origin[0],",y:").concat(origin[1],"}");this.map.addLayer({id:(0,_lodash.default)(layerInfo.name+'-'),// @ts-ignore type:style.mbglType,source:{type:'vector',tiles:[url]},'source-layer':"".concat(info.datasetName,"@").concat(info.datasourceName),paint:paint,layout:{visibility:layerInfo.visible?'visible':'none'}});}},{key:"_isMvt",value:function _isMvt(serviceUrl,datasetName){var _this14=this;return this._getDatasetsInfo(serviceUrl,datasetName).then(function(info){//判断是否和底图坐标系一直 if(info.epsgCode==_this14.baseProjection.split('EPSG:')[1]){return SuperMap.FetchRequest.get("".concat(info.url,"/tilefeature.mvt")).then(function(response){return response.json();}).then(function(result){info.isMvt=result.error&&result.error.code===400;return info;}).catch(function(){return info;});}return info;});}},{key:"_getDatasetsInfo",value:function _getDatasetsInfo(serviceUrl,datasetName){return this._getDatasources(serviceUrl).then(function(datasourceName){//判断mvt服务是否可用 var url="".concat(serviceUrl,"/data/datasources/").concat(datasourceName,"/datasets/").concat(datasetName);return SuperMap.FetchRequest.get(url).then(function(response){return response.json();}).then(function(datasetsInfo){return{epsgCode:datasetsInfo.datasetInfo.prjCoordSys.epsgCode,bounds:datasetsInfo.datasetInfo.bounds,datasourceName:datasourceName,datasetName:datasetName,url:url//返回的是原始url,没有代理。因为用于请求mvt };});});}},{key:"_getDataVectorTileStyle",value:function _getDataVectorTileStyle(featureType){var styleParameters={radius:8,//圆点半径 fillColor:'#EE4D5A',//填充色 fillOpacity:0.9,strokeColor:'#ffffff',//边框颜色 strokeWidth:1,strokeOpacity:1,lineDash:'solid',type:'BASIC_POINT',mbglType:'circle'};if(['LINE','LINESTRING','MULTILINESTRING'].includes(featureType)){styleParameters.strokeColor='#4CC8A3';styleParameters.strokeWidth=2;styleParameters.mbglType='line';}else if(['REGION','POLYGON','MULTIPOLYGON'].includes(featureType)){styleParameters.fillColor='#826DBA';styleParameters.mbglType='fill';}return styleParameters;}},{key:"_transformFeatures",value:function _transformFeatures(features){var _this15=this;features&&features.forEach(function(feature,index){var geometryType=feature.geometry.type;var coordinates=feature.geometry.coordinates;if(geometryType==='LineString'){coordinates.forEach(function(coordinate,index){coordinate=_this15._unproject(coordinate);coordinates[index]=coordinate;},_this15);}else if(geometryType==='Point'){coordinates=_this15._unproject(coordinates);feature.geometry.coordinates=coordinates;}else if(geometryType==='MultiPolygon'||geometryType==='Polygon'){coordinates.forEach(function(coordinate,index){var coords=geometryType==='MultiPolygon'?coordinate[0]:coordinate;coords.forEach(function(latlng,index){latlng=_this15._unproject(latlng);coords[index]=latlng;});coordinates[index]=coordinate;});}features[index]=feature;},this);}}]);return WebMapViewModel;}(_mapboxGlEnhance.default.Evented);exports["default"]=WebMapViewModel; /***/ }), /***/ 4831: /***/ (function(__unused_webpack_module, exports) { "use strict"; Object.defineProperty(exports, "__esModule", ({value:true}));exports.MAP_EVENT_NAMES=void 0;var MAP_EVENT_NAMES=['onResize','onWebglcontextlost','onWebglcontextrestored','onRemove','onMovestart','onContextmenu','onDblclick','onClick','onTouchcancel','onTouchmove','onTouchend','onTouchstart','onDataloading','onMousemove','onMouseup','onMousedown','onSourcedataloading','onError','onData','onStyledata','onSourcedata','onMouseout','onStyledataloading','onMoveend','onMove','onRender','onZoom','onZoomstart','onZoomend','onBoxzoomstart','onBoxzoomcancel','onBoxzoomend','onRotate','onRotatestart','onRotateend','onDragend','onDrag','onDragstart','onPitch','onIdle'];exports.MAP_EVENT_NAMES=MAP_EVENT_NAMES;; /***/ }), /***/ 5558: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var _interopRequireDefault=(__webpack_require__(4836)["default"]);Object.defineProperty(exports, "__esModule", ({value:true}));exports["default"]=void 0;var _classCallCheck2=_interopRequireDefault(__webpack_require__(5671));var _createClass2=_interopRequireDefault(__webpack_require__(3144));var _inherits2=_interopRequireDefault(__webpack_require__(9340));var _createSuper2=_interopRequireDefault(__webpack_require__(8557));var _compose2=_interopRequireDefault(__webpack_require__(8808));var _react=_interopRequireDefault(__webpack_require__(3899));var _mapGetter=_interopRequireDefault(__webpack_require__(9635));var _baseLayer=_interopRequireDefault(__webpack_require__(7006));var _dec,_class;var Layer=(_dec=(0,_compose2.default)(_mapGetter.default,_baseLayer.default),_dec(_class=/*#__PURE__*/function(_React$Component){(0,_inherits2.default)(Layer,_React$Component);var _super=(0,_createSuper2.default)(Layer);function Layer(){(0,_classCallCheck2.default)(this,Layer);return _super.apply(this,arguments);}(0,_createClass2.default)(Layer,[{key:"loaded",value:function loaded(map){var _this$props=this.props,type=_this$props.type,source=_this$props.source,layerId=_this$props.layerId,minzoom=_this$props.minzoom,maxzoom=_this$props.maxzoom,filter=_this$props.filter,layout=_this$props.layout,paint=_this$props.paint,metadata=_this$props.metadata;if(map.getLayer(layerId)){console.error("There is already a layer with the id \"".concat(layerId,"\""));return;}if(typeof source==='string'&&!map.getSource(source)){console.error("Source \"".concat(source,"\" is not loaded"));return;}if(type!=='background'&&!source){console.error("Source is required unless type is background");return;}var layerOption={id:layerId,type:type};source&&(layerOption.source=source);minzoom!==undefined&&(layerOption.minzoom=minzoom);maxzoom!==undefined&&(layerOption.maxzoom=maxzoom);filter&&(layerOption.filter=filter);layout&&(layerOption.layout=layout);paint&&(layerOption.paint=paint);metadata&&(layerOption.metadata=metadata);this.props['source-layer']&&(layerOption['source-layer']=this.props['source-layer']);map.addLayer(layerOption);}},{key:"removed",value:function removed(){}},{key:"render",value:function render(){return null;}}]);return Layer;}(_react.default.Component))||_class);exports["default"]=Layer; /***/ }), /***/ 1193: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var _interopRequireDefault=(__webpack_require__(4836)["default"]);Object.defineProperty(exports, "__esModule", ({value:true}));exports["default"]=void 0;var _classCallCheck2=_interopRequireDefault(__webpack_require__(5671));var _createClass2=_interopRequireDefault(__webpack_require__(3144));var _inherits2=_interopRequireDefault(__webpack_require__(9340));var _createSuper2=_interopRequireDefault(__webpack_require__(8557));var _react=__webpack_require__(3899);var _lodash=_interopRequireDefault(__webpack_require__(2307));var _mapGetter=_interopRequireDefault(__webpack_require__(9635));var _AnimateMarkerLayerViewModel=_interopRequireDefault(__webpack_require__(3843));var _BreathingApertureMarker=_interopRequireDefault(__webpack_require__(7278));var _DiffusedApertureMarker=_interopRequireDefault(__webpack_require__(2017));var _HaloRingMarker=_interopRequireDefault(__webpack_require__(6130));var _RotatingApertureMarker=_interopRequireDefault(__webpack_require__(970));var _RotatingTextBorderMarker=_interopRequireDefault(__webpack_require__(9041));var _FluorescenceMarker=_interopRequireDefault(__webpack_require__(6889));var _class,_class2;var AnimateMarkerLayer=(0,_mapGetter.default)(_class=(_class2=/*#__PURE__*/function(_Component){(0,_inherits2.default)(AnimateMarkerLayer,_Component);var _super=(0,_createSuper2.default)(AnimateMarkerLayer);function AnimateMarkerLayer(){(0,_classCallCheck2.default)(this,AnimateMarkerLayer);return _super.apply(this,arguments);}(0,_createClass2.default)(AnimateMarkerLayer,[{key:"componentDidMount",value:function componentDidMount(){this._markersElement=[];}},{key:"componentDidUpdate",value:function componentDidUpdate(prevProps){if(this.viewModel&&!(0,_lodash.default)(prevProps.features,this.props.features)){this._markersElement=[];this._getMarkerElement();this.props.features&&this.viewModel.setFeatures(this.props.features,this._markersElement);}if(this.viewModel&&!(0,_lodash.default)(prevProps.type,this.props.type)){this._markersElement=[];this._getMarkerElement();this.viewModel.setType(this._markersElement);}if(this.viewModel&&this.props.width&&prevProps.width!==this.props.width){this.marker&&this.marker.setMarkersWidth(this.props.width);}if(this.viewModel&&this.props.height&&prevProps.height!==this.props.height){this.marker&&this.marker.setMarkersHeight&&this.marker.setMarkersHeight(this.props.height);}if(this.viewModel&&this.props.textColor&&prevProps.textColor!==this.props.textColor){this.marker&&this.marker.setMarkersTextColor(this.props.textColor);}if(this.viewModel&&this.props.textFontSize&&prevProps.textFontSize!==this.props.textFontSize){this.marker&&this.marker.setMarkersTextFontSize(this.props.textFontSize);}if(this.viewModel&&this.props.colors&&this.props.colors.length&&this.props.colors.length>0&&!(0,_lodash.default)(prevProps.colors,this.props.colors)){this.marker&&this.marker.setMarkersColors(this.props.colors);}if(this.viewModel&&this.props.textField&&prevProps.textField!==this.props.textField){this.marker&&this.marker.setMarkersTextField(this.props.textField);}}},{key:"componentWillUnmount",value:function componentWillUnmount(){this.viewModel&&this.viewModel.clearMarkerLayer();}},{key:"loaded",value:function loaded(map){this.props.features&&this._getMarkerElement();this.viewModel=new _AnimateMarkerLayerViewModel.default(map,this.props.features,this._markersElement,this.props.fitBounds);}},{key:"_getMarkerElement",value:function _getMarkerElement(){this.setState({marker:null});var _this$props=this.props,features=_this$props.features,width=_this$props.width,height=_this$props.height,colors=_this$props.colors,textFontSize=_this$props.textFontSize,textColor=_this$props.textColor,textField=_this$props.textField,type=_this$props.type;if(!features||JSON.stringify(features)==='{}'||!features.features){this.viewModel&&this.viewModel.clearMarkerLayer();return;}switch(type){case'rotatingAperture':this.marker=new _RotatingApertureMarker.default(features,{width:width,colors:colors,textField:textField,textColor:textColor,textFontSize:textFontSize});break;case'haloRing':this.marker=new _HaloRingMarker.default(features,{width:width,colors:colors,textField:textField,textColor:textColor,textFontSize:textFontSize});break;case'breathingAperture':this.marker=new _BreathingApertureMarker.default(features,{width:width,colors:colors,textField:textField,textColor:textColor,textFontSize:textFontSize});break;case'diffusedAperture':this.marker=new _DiffusedApertureMarker.default(features,{width:width,colors:colors,textField:textField,textColor:textColor,textFontSize:textFontSize});break;case'rotatingTextBorder':this.marker=new _RotatingTextBorderMarker.default(features,{width:width,height:height,colors:colors,textField:textField,textColor:textColor,textFontSize:textFontSize});break;case'fluorescence':this.marker=new _FluorescenceMarker.default(features,{width:width,colors:colors,textField:textField,textColor:textColor,textFontSize:textFontSize});break;}this.marker&&(this._markersElement=this.marker.getMarkersElement());}},{key:"render",value:function render(){return null;}}]);return AnimateMarkerLayer;}(_react.Component),_class2.defaultProps={type:'breathingAperture',textFontSize:14},_class2))||_class;exports["default"]=AnimateMarkerLayer; /***/ }), /***/ 3843: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var _interopRequireDefault=(__webpack_require__(4836)["default"]);Object.defineProperty(exports, "__esModule", ({value:true}));exports["default"]=void 0;var _classCallCheck2=_interopRequireDefault(__webpack_require__(5671));var _createClass2=_interopRequireDefault(__webpack_require__(3144));var _inherits2=_interopRequireDefault(__webpack_require__(9340));var _createSuper2=_interopRequireDefault(__webpack_require__(8557));var _mapboxGlEnhance=_interopRequireDefault(__webpack_require__(375));var _envelope=_interopRequireDefault(__webpack_require__(3880));var _bbox=_interopRequireDefault(__webpack_require__(9705));var _transformScale=_interopRequireDefault(__webpack_require__(5748));var AnimateMarkerLayerViewModel=/*#__PURE__*/function(_mapboxgl$Evented){(0,_inherits2.default)(AnimateMarkerLayerViewModel,_mapboxgl$Evented);var _super=(0,_createSuper2.default)(AnimateMarkerLayerViewModel);function AnimateMarkerLayerViewModel(map,features,markersElement){var _this;var fitBounds=arguments.length>3&&arguments[3]!==undefined?arguments[3]:true;(0,_classCallCheck2.default)(this,AnimateMarkerLayerViewModel);_this=_super.call(this);if(!map){throw new Error('map is requierd');}_this.map=map;_this.features=features;_this.markers=[];_this.markersElement=markersElement;_this.fitBounds=fitBounds;_this.features&&_this._initalizeMarkerLayer();return _this;}(0,_createClass2.default)(AnimateMarkerLayerViewModel,[{key:"setType",value:function setType(markersElement){this.markersElement=markersElement;this._initalizeMarkerLayer();}},{key:"setFeatures",value:function setFeatures(features,markersElement){this.markersElement=markersElement;this.features=features;this._initalizeMarkerLayer();}},{key:"_initalizeMarkerLayer",value:function _initalizeMarkerLayer(){if(!this.features||JSON.stringify(this.features)==='{}'){return;}this.clearMarkerLayer();this._createMarker();}},{key:"_createMarker",value:function _createMarker(){var _this2=this;this.features.features.forEach(function(point,index){var marker=new _mapboxGlEnhance.default.Marker(_this2.markersElement[index]||_this2.markersElement[0])// @ts-ignore .setLngLat(point.geometry.coordinates).addTo(_this2.map);_this2.markers.push(marker);},this);if(this.fitBounds){// @ts-ignore var bounds=(0,_bbox.default)((0,_transformScale.default)((0,_envelope.default)(this.features),1.7));this.fitBounds&&this.map.fitBounds([[bounds[0],bounds[1]],[bounds[2],bounds[3]]],{maxZoom:17});}}},{key:"clearMarkerLayer",value:function clearMarkerLayer(){this.markers.length>0&&this.markers.forEach(function(marker){marker&&marker.remove();});this.markers=[];}}]);return AnimateMarkerLayerViewModel;}(_mapboxGlEnhance.default.Evented);exports["default"]=AnimateMarkerLayerViewModel; /***/ }), /***/ 7278: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var _interopRequireDefault=(__webpack_require__(4836)["default"]);Object.defineProperty(exports, "__esModule", ({value:true}));exports["default"]=void 0;var _classCallCheck2=_interopRequireDefault(__webpack_require__(5671));var _createClass2=_interopRequireDefault(__webpack_require__(3144));var _inherits2=_interopRequireDefault(__webpack_require__(9340));var _createSuper2=_interopRequireDefault(__webpack_require__(8557));var _Marker2=_interopRequireDefault(__webpack_require__(9853));var BreathingApertureMarker=/*#__PURE__*/function(_Marker){(0,_inherits2.default)(BreathingApertureMarker,_Marker);var _super=(0,_createSuper2.default)(BreathingApertureMarker);function BreathingApertureMarker(features){var _this;var options=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};(0,_classCallCheck2.default)(this,BreathingApertureMarker);_this=_super.call(this,features,options);_this.features&&_this._createMarker();return _this;}(0,_createClass2.default)(BreathingApertureMarker,[{key:"setMarkersWidth",value:function setMarkersWidth(width){this.options.width=width;var pulse=document.getElementsByClassName('sm-component-animate-marker__pulse');for(var i=0;i0){var dot=document.getElementsByClassName('sm-component-animate-marker__dot-point');for(var i=0;i0){colors=_this2.options.colors;}colors&&(dot.style.background=colors[0]);markerContainer.appendChild(dot);var childElements=_this2._createMakerElement(3,'span',['sm-component-animate-marker__delay','sm-component-animate-marker__pulse']);childElements.forEach(function(element){if(colors){element.style.borderColor=colors[0];element.style.boxShadow="0 0 12px ".concat(colors[1],", 0 0 20px ").concat(colors[1]," inset");}_this2._setBreathingApertureWidth(element.style);markerContainer.appendChild(element);});var nameContainer=_this2._getTextContainer(point,'breathing-aperture-name');markerContainer.appendChild(nameContainer);_this2.markersElement.push(markerContainer);},this);}},{key:"_setBreathingApertureWidth",value:function _setBreathingApertureWidth(style){var width=this.options.width;if(width){style.width=width+'px';style.height=width+'px';style.top=-width/2+'px';style.left=-width/2+'px';style.borderRadius=width/2+'px';}}},{key:"_createMakerElement",value:function _createMakerElement(length,type,classNames){var markerElements=[];for(var i=1;i1&&arguments[1]!==undefined?arguments[1]:{};(0,_classCallCheck2.default)(this,DiffusedApertureMarker);_this=_super.call(this,features,options);_this.features&&_this._createMarker();return _this;}(0,_createClass2.default)(DiffusedApertureMarker,[{key:"setMarkersWidth",value:function setMarkersWidth(width){this.options.width=width;var markerContainer=document.getElementsByClassName('sm-component-animate-marker--diffused-aperture');for(var i=0;i0){var markerContainer=document.getElementsByClassName('sm-component-animate-marker--diffused-aperture');for(var i=0;i0){markerContainer.style.setProperty('--background-color',_this2.options.colors[0]);markerContainer.style.setProperty('--box-shadow-color',_this2.options.colors[1]||_this2.options.colors[0]);}_this2.markersElement.push(markerContainer);},this);}}]);return DiffusedApertureMarker;}(_Marker2.default);exports["default"]=DiffusedApertureMarker; /***/ }), /***/ 6889: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var _interopRequireDefault=(__webpack_require__(4836)["default"]);Object.defineProperty(exports, "__esModule", ({value:true}));exports["default"]=void 0;var _classCallCheck2=_interopRequireDefault(__webpack_require__(5671));var _createClass2=_interopRequireDefault(__webpack_require__(3144));var _inherits2=_interopRequireDefault(__webpack_require__(9340));var _createSuper2=_interopRequireDefault(__webpack_require__(8557));var _Marker2=_interopRequireDefault(__webpack_require__(9853));var FluorescenceMarker=/*#__PURE__*/function(_Marker){(0,_inherits2.default)(FluorescenceMarker,_Marker);var _super=(0,_createSuper2.default)(FluorescenceMarker);function FluorescenceMarker(features){var _this;var options=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};(0,_classCallCheck2.default)(this,FluorescenceMarker);_this=_super.call(this,features,options);_this.features&&_this._createMarker();return _this;}(0,_createClass2.default)(FluorescenceMarker,[{key:"setMarkersWidth",value:function setMarkersWidth(width){this.options.width=width;var markerContainer=document.getElementsByClassName('sm-component-animate-marker--fluorescence');for(var i=0;i0){var markerContainer=document.getElementsByClassName('sm-component-animate-marker--fluorescence');for(var i=0;i0){style.setProperty('--box-shadow-color',this.options.colors[0]);style.setProperty('--light-color',this.options.colors[1]);}}}]);return FluorescenceMarker;}(_Marker2.default);exports["default"]=FluorescenceMarker; /***/ }), /***/ 6130: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var _interopRequireDefault=(__webpack_require__(4836)["default"]);Object.defineProperty(exports, "__esModule", ({value:true}));exports["default"]=void 0;var _classCallCheck2=_interopRequireDefault(__webpack_require__(5671));var _createClass2=_interopRequireDefault(__webpack_require__(3144));var _inherits2=_interopRequireDefault(__webpack_require__(9340));var _createSuper2=_interopRequireDefault(__webpack_require__(8557));var _colorcolor=_interopRequireDefault(__webpack_require__(9458));var _Marker2=_interopRequireDefault(__webpack_require__(9853));var HaloRingMarker=/*#__PURE__*/function(_Marker){(0,_inherits2.default)(HaloRingMarker,_Marker);var _super=(0,_createSuper2.default)(HaloRingMarker);function HaloRingMarker(features){var _this;var options=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};(0,_classCallCheck2.default)(this,HaloRingMarker);_this=_super.call(this,features,options);_this.features&&_this._createMarker();return _this;}(0,_createClass2.default)(HaloRingMarker,[{key:"setMarkersWidth",value:function setMarkersWidth(width){this.options.width=width;var markerContainer=document.getElementsByClassName('sm-component-animate-marker--halo-ring');for(var i=0;i0){var markerContainer=document.getElementsByClassName('sm-component-animate-marker--halo-ring');for(var i=0;i0){markerContainer.style.setProperty('--color-1',_this2._getColorWithOpacity((0,_colorcolor.default)(_this2.options.colors[0],'rgba',true),0.3));markerContainer.style.setProperty('--color-1-transparent',_this2._getColorWithOpacity((0,_colorcolor.default)(_this2.options.colors[0],'rgba',true),0.1));markerContainer.style.setProperty('--color-2',_this2._getColorWithOpacity((0,_colorcolor.default)(_this2.options.colors[1],'rgba',true),0.3));markerContainer.style.setProperty('--color-2-transparent',_this2._getColorWithOpacity((0,_colorcolor.default)(_this2.options.colors[1],'rgba',true),0.1));}_this2.markersElement.push(markerContainer);},this);}},{key:"_createMakerElement",value:function _createMakerElement(length,type,classNames){var markerElements=[];for(var i=1;i1&&arguments[1]!==undefined?arguments[1]:{};(0,_classCallCheck2.default)(this,Marker);this.markersElement=[];this.features=features;this.options=options;}(0,_createClass2.default)(Marker,[{key:"setFeatures",value:function setFeatures(features){this.markersElement=[];this.features=features;this.features&&this._createMarker();}},{key:"getMarkersElement",value:function getMarkersElement(){return this.markersElement;}},{key:"setMarkersTextField",value:function setMarkersTextField(textField){if(!this.features||JSON.stringify(this.features)==='{}'){return;}this.options.textField=textField;var name=document.getElementsByClassName('sm-component-animate-marker__name');for(var i=0;i1&&arguments[1]!==undefined?arguments[1]:{};(0,_classCallCheck2.default)(this,RotatingApertureMarker);_this=_super.call(this,features,options);_this.features&&_this._createMarker();return _this;}(0,_createClass2.default)(RotatingApertureMarker,[{key:"setMarkersWidth",value:function setMarkersWidth(width){this.options.width=width;// TODO 待抛出 width 不能小于 40 if(!this.options.width||this.options.width<40){return;}var dotsMarker=document.getElementsByClassName('sm-component-animate-marker--rotating-aperture');for(var i=0;i0){var dotsMarker=document.getElementsByClassName('sm-component-animate-marker--rotating-aperture');for(var i=0;i=40?_this2.options.width:50;var markerContainer=document.createElement('div');markerContainer.className='sm-component-animate-marker--rotating-aperture';var childElements=_this2._createMakerElement(3,'div',['sm-component-animate-marker__dots','sm-component-animate-marker__dots']);childElements.forEach(function(element,index){var elementWidth;index===0&&(elementWidth=width-32);index===1&&(elementWidth=width-16);index===2&&(elementWidth=width);element.setAttribute('style',_this2._getDotsStyleObj(elementWidth));markerContainer.appendChild(element);});var nameContainer=_this2._getTextContainer(point,'rotating-aperture-name');markerContainer.appendChild(nameContainer);if(_this2.options.colors&&_this2.options.colors.length&&_this2.options.colors.length>0&&_this2.options.colors[0].indexOf('rgb')>-1){markerContainer.style.setProperty('--color',_this2.options.colors[0]);markerContainer.style.setProperty('--line-color',_this2._getColorWithOpacity(_this2.options.colors[0],0.2));markerContainer.style.setProperty('--light-color',_this2.options.colors[1]);}markerContainer.style.setProperty('--container-width',width+'px');_this2.markersElement.push(markerContainer);},this);}},{key:"_createMakerElement",value:function _createMakerElement(length,type,classNames){var markerElements=[];for(var i=1;i1&&arguments[1]!==undefined?arguments[1]:{};(0,_classCallCheck2.default)(this,RotatingTextBorderMarker);_this=_super.call(this,features);_this.options=options;_this.features&&_this._createMarker();return _this;}(0,_createClass2.default)(RotatingTextBorderMarker,[{key:"setMarkersWidth",value:function setMarkersWidth(width){this.options.width=width;this._setMarkerContainerProperty({'--clip-width-1':width+width/10+'px','--clip-width-2':width+width/10-2+'px','--boder-width':width+'px','--text-left-position':-width/2+'px'});}},{key:"setMarkersHeight",value:function setMarkersHeight(height){this.options.height=height;this._setMarkerContainerProperty({'--clip-height-1':height+height/10+'px','--clip-height-2':height+height/10-2+'px','--boder-height':height+'px'});}},{key:"setMarkersTextField",value:function setMarkersTextField(textField){if(!this.features||JSON.stringify(this.features)==='{}'){return;}this.options.textField=textField;var name=document.getElementsByClassName('sm-component-animate-marker__text');for(var i=0;i0){this._setMarkerContainerProperty({'--border-color':colors[0],'--box-shadow-color':colors[1]});}}},{key:"_createMarker",value:function _createMarker(){var _this2=this;this.features.features.forEach(function(point){var markerContainer=document.createElement('div');markerContainer.className='sm-component-animate-marker--text-boder';var border=document.createElement('div');border.className='sm-component-animate-marker__boder';var keys=Object.keys(point.properties);var name;if(point.properties||Object.keys(point.properties).length!==0){name=point.properties[_this2.options.textField]||point.properties[keys[0]];}var span=document.createElement('span');span.className='sm-component-animate-marker__text';span.innerHTML=name||'';border.appendChild(span);if(_this2.options.colors&&_this2.options.colors.length&&_this2.options.colors.length>0){markerContainer.style.setProperty('--border-color',_this2.options.colors[0]);markerContainer.style.setProperty('--box-shadow-color',_this2.options.colors[1]);}_this2.options.textColor&&markerContainer.style.setProperty('--text-color',_this2.options.textColor);_this2.options.textFontSize&&markerContainer.style.setProperty('--text-font-size',_this2.options.textFontSize+'px');if(_this2.options.width){markerContainer.style.setProperty('--clip-width-1',_this2.options.width+_this2.options.width/10+'px');markerContainer.style.setProperty('--clip-width-2',_this2.options.width+_this2.options.width/10-2+'px');markerContainer.style.setProperty('--boder-width',_this2.options.width+'px');markerContainer.style.setProperty('--text-left-position',-_this2.options.width/2+'px');}if(_this2.options.height){markerContainer.style.setProperty('--clip-height-1',_this2.options.height+_this2.options.width/10+'px');markerContainer.style.setProperty('--clip-height-2',_this2.options.height+_this2.options.width/10-2+'px');markerContainer.style.setProperty('--boder-height',_this2.options.height+'px');}if((_this2.options.width||100)>(_this2.options.width||200)){markerContainer.style.setProperty('--animation-name','clipMe2');}else{markerContainer.style.setProperty('--animation-name','clipMe1');}markerContainer.appendChild(border);_this2.markersElement.push(markerContainer);},this);}},{key:"_setMarkerContainerProperty",value:function _setMarkerContainerProperty(properties){var _this3=this;var markerContainer=document.getElementsByClassName('sm-component-animate-marker--text-boder');var _loop=function _loop(){// @ts-ignore var style=markerContainer[i].style;Object.keys(properties).forEach(function(key){style.setProperty(key,properties[key]);});if((_this3.options.height||100)>(_this3.options.width||200)){style.setProperty('--animation-name','clipMe2');}else{style.setProperty('--animation-name','clipMe1');}};for(var i=0;i2&&arguments[2]!==undefined?arguments[2]:{};(0,_classCallCheck2.default)(this,ClusterLayerViewModel);_this=_super.call(this);_this.options=options;if(!map){throw new Error('map is requierd');}_this.map=map;_this.data=data;_this.layerId=options.layerId||'clusterLayer'+new Date().getTime();_this.data&&_this._initializeClusterLayer();return _this;}(0,_createClass2.default)(ClusterLayerViewModel,[{key:"setData",value:function setData(data){if(!data){return;}this.data=data;if(this.layerId&&!this.map.getSource(this.layerId)){this._initializeClusterLayer();}else{this.map.getSource(this.layerId).setData(data);}}},{key:"setClusteredPointStyle",value:function setClusteredPointStyle(clusteredPointStyle){if(!clusteredPointStyle||this.layerId&&!this.map.getSource(this.layerId)){return;}this.options.clusteredPointStyle=clusteredPointStyle;this._setPaintProperty(clusteredPointStyle.paint,this.layerId);this._setLayoutProperty(clusteredPointStyle.layout,this.layerId);}},{key:"setUnclusteredPointStyle",value:function setUnclusteredPointStyle(unclusteredPointStyle){var layerId='unclustered_point'+this.layerId;if(!unclusteredPointStyle||!this.map.getSource(layerId)){return;}this.options.unclusteredPointStyle=unclusteredPointStyle;this._setPaintProperty(unclusteredPointStyle.paint,layerId);this._setLayoutProperty(unclusteredPointStyle.layout,layerId);}},{key:"setClusteredPointTextLayout",value:function setClusteredPointTextLayout(clusteredPointTextLayout){var layerId='count_'+this.layerId;if(!clusteredPointTextLayout||!this.map.getSource(layerId)){return;}this.options.clusteredPointTextLayout=clusteredPointTextLayout;this._setLayoutProperty(clusteredPointTextLayout,layerId);}},{key:"_setPaintProperty",value:function _setPaintProperty(paint,layerId){var _this2=this;Object.keys(paint).forEach(function(key){_this2.map.setPaintProperty(layerId,key,paint[key]);});}},{key:"_setLayoutProperty",value:function _setLayoutProperty(layout,layerId){var _this3=this;Object.keys(layout).forEach(function(key){_this3.map.setLayoutProperty(layerId,key,layout[key]);});}},{key:"_initializeClusterLayer",value:function _initializeClusterLayer(){var _this4=this;this.map.addSource(this.layerId,{type:'geojson',data:this.data,cluster:true,clusterMaxZoom:this.options.maxZoom||14,clusterRadius:this.options.radius||50});this.map.addLayer({id:this.layerId,type:'circle',source:this.layerId,filter:['has','point_count'],paint:this.options.clusteredPointStyle&&this.options.clusteredPointStyle.paint||{'circle-color':['step',['get','point_count'],'#51bbd6',100,'#f1f075',750,'#f28cb1'],'circle-radius':['step',['get','point_count'],20,100,30,750,40]}});// 聚合点文本 layer this.map.addLayer({id:'count_'+this.layerId,type:'symbol',source:this.layerId,filter:['has','point_count'],layout:this.options.clusteredPointTextLayout||{'text-field':'{point_count_abbreviated}','text-font':['DIN Offc Pro Medium','Arial Unicode MS Bold'],'text-size':12}});// 未聚合点 layer this.map.addLayer({id:'unclustered_point'+this.layerId,type:'circle',source:this.layerId,filter:['!',['has','point_count']],paint:this.options.unclusteredPointStyle&&this.options.unclusteredPointStyle.paint||{'circle-color':'#11b4da','circle-radius':4,'circle-stroke-width':1,'circle-stroke-color':'#fff'}});/** * @event addcusterlayersucceeded * @description 添加点聚合图层成功后触发。 * @property {Object} map - mapboxgl map 对象。 */this.fire('addcusterlayersucceeded',{map:this.map});this.map.on('click',this.layerId,function(e){var features=_this4.map.queryRenderedFeatures(e.point,{layers:[_this4.layerId]});var clusterId=features[0].properties.cluster_id;_this4.map.getSource(_this4.layerId).getClusterExpansionZoom(clusterId,function(err,zoom){if(err)return;_this4.map.easeTo({center:features[0].geometry.coordinates,zoom:zoom});});});this.map.on('mouseenter',this.layerId,function(){_this4.map.getCanvas().style.cursor='pointer';});this.map.on('mouseleave',this.layerId,function(){_this4.map.getCanvas().style.cursor='';});}}]);return ClusterLayerViewModel;}(_mapboxGlEnhance.default.Evented);exports["default"]=ClusterLayerViewModel; /***/ }), /***/ 2313: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var _interopRequireDefault=(__webpack_require__(4836)["default"]);Object.defineProperty(exports, "__esModule", ({value:true}));exports["default"]=void 0;var _objectSpread2=_interopRequireDefault(__webpack_require__(8683));var _classCallCheck2=_interopRequireDefault(__webpack_require__(5671));var _createClass2=_interopRequireDefault(__webpack_require__(3144));var _inherits2=_interopRequireDefault(__webpack_require__(9340));var _createSuper2=_interopRequireDefault(__webpack_require__(8557));var _compose2=_interopRequireDefault(__webpack_require__(8808));var _react=_interopRequireDefault(__webpack_require__(3899));var _mapGetter=_interopRequireDefault(__webpack_require__(9635));var _baseLayer=_interopRequireDefault(__webpack_require__(7006));var _DataFlowLayerViewModel=_interopRequireDefault(__webpack_require__(9162));var _types=__webpack_require__(2009);var _util=__webpack_require__(9752);var _dec,_class,_class2;var DataFlowLayer=(_dec=(0,_compose2.default)(_mapGetter.default,_baseLayer.default),_dec(_class=(_class2=/*#__PURE__*/function(_React$Component){(0,_inherits2.default)(DataFlowLayer,_React$Component);var _super=(0,_createSuper2.default)(DataFlowLayer);function DataFlowLayer(){(0,_classCallCheck2.default)(this,DataFlowLayer);return _super.apply(this,arguments);}(0,_createClass2.default)(DataFlowLayer,[{key:"loaded",value:function loaded(map){var options=JSON.parse(JSON.stringify(this.props));delete options.serviceUrl;this.viewModel=new _DataFlowLayerViewModel.default(map,this.props.serviceUrl,(0,_objectSpread2.default)({},options));this.registerEvents();}},{key:"registerEvents",value:function registerEvents(){var _this=this;// @ts-ignore this.viewModel.on('subscribefailed',function(e){// this.$message.error(this.$t('dataFlow.dataSubscriptionFailed')); /** * @event subscribeFailed * @desc 数据订阅失败后触发。 * @property {Object} e - 事件对象。 */(0,_util.isFunction)(_this.props.onSubscribeFailed)&&_this.props.onSubscribeFailed(e);});// @ts-ignore this.viewModel.on('subscribesucceeded',function(e){/** * @event subscribeSucceeded * @desc 数据订阅失败后触发。 * @property {Object} e - 事件对象。 */(0,_util.isFunction)(_this.props.onSubscribeSucceeded)&&_this.props.onSubscribeSucceeded(e);});// @ts-ignore this.viewModel.on('dataupdated',function(e){/** * @event dataUpdated * @desc 数据更新成功后触发。 * @property {GeoJSONObject} data - 更新的数据。 * @property {mapboxgl.Map} map - MapBoxGL Map 对象。 */(0,_util.isFunction)(_this.props.onDataUpdated)&&_this.props.onDataUpdated(e);});}},{key:"render",value:function render(){return null;}}]);return DataFlowLayer;}(_react.default.Component),_class2.defaultProps={layerStyle:{line:new _types.LineStyle(),circle:new _types.CircleStyle(),fill:new _types.FillStyle()}},_class2))||_class);exports["default"]=DataFlowLayer; /***/ }), /***/ 9162: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var _interopRequireDefault=(__webpack_require__(4836)["default"]);Object.defineProperty(exports, "__esModule", ({value:true}));exports["default"]=void 0;var _classCallCheck2=_interopRequireDefault(__webpack_require__(5671));var _createClass2=_interopRequireDefault(__webpack_require__(3144));var _inherits2=_interopRequireDefault(__webpack_require__(9340));var _createSuper2=_interopRequireDefault(__webpack_require__(8557));var _lodash=_interopRequireDefault(__webpack_require__(3465));var _mapboxGlEnhance=_interopRequireDefault(__webpack_require__(375));__webpack_require__(2395);/** * @class DataFlowLayerViewModel * @category ViewModel * @classdesc 数据流图层组件功能类。 * @param {mapboxgl.Map} map - mapboxgl map 对象。 * @param {String} serviceUrl - 数据流服务地址。 * @param {Object} [options] - 可选参数。 * @param {String} [options.layerId] - 图层 ID。 * @param {Object} [options.layerStyle] - 指定图层样式。 * @param {GeoJSONObject} [options.geometry] - 指定几何范围,该范围内的要素才能被订阅。 * @param {String} [options.excludeField] - 排除字段。 * @param {Object} [options.styleOptions] - style OPtion * @fires DataFlowLayerViewModel#subscribesucceeded * @fires DataFlowLayerViewModel#subscribefailed * @fires DataFlowLayerViewModel#dataUpdated */var DataFlowLayerViewModel=/*#__PURE__*/function(_mapboxgl$Evented){(0,_inherits2.default)(DataFlowLayerViewModel,_mapboxgl$Evented);var _super=(0,_createSuper2.default)(DataFlowLayerViewModel);function DataFlowLayerViewModel(map,serviceUrl,options){var _this;(0,_classCallCheck2.default)(this,DataFlowLayerViewModel);_this=_super.call(this);if(!serviceUrl){throw new Error('serviceUrl is requierd');}if(!map){throw new Error('map is requierd');}_this.options=options||{};_this.map=map;_this.serviceUrl=serviceUrl;_this.sourceID=options.layerId||'dataFlow'+new Date().getTime();_this.layerStyle=options.layerStyle||{};if(_this.options.registerToken){SuperMap.SecurityManager.registerToken(_this.serviceUrl,_this.options.registerToken);}_this._initializeDataFlow();return _this;}(0,_createClass2.default)(DataFlowLayerViewModel,[{key:"setLayerStyle",value:function setLayerStyle(layerStyle){this.layerStyle=layerStyle;}/** * @function DataFlowLayerViewModel.prototype.setExcludeField * @description 设置唯一字段。 * @param {string} excludeField - 唯一字段。 */},{key:"setExcludeField",value:function setExcludeField(excludeField){this.dataService.setExcludeField(excludeField);this.options.excludeField=excludeField;return this;}/** * @function DataFlowLayerViewModel.prototype.setGeometry * @description 设置集合要素。 * @param {GeoJSONObject} geometry - 待设置的 GeoJSON 几何要素对象。 */},{key:"setGeometry",value:function setGeometry(geometry){this.dataService.setGeometry(geometry);this.options.geometry=geometry;return this;}},{key:"_initializeDataFlow",value:function _initializeDataFlow(){var _this2=this;var dataService=new _mapboxGlEnhance.default.supermap.DataFlowService(this.serviceUrl,{geometry:this.options.geometry,excludeField:this.options.excludeField}).initSubscribe();dataService.on('subscribeSocketConnected',function(e){/** * @event DataFlowLayerViewModel#subscribesucceeded * @description 数据订阅成功后触发。 * @property {Object} e - 事件对象。 */_this2.fire('subscribesucceeded',e);});dataService.on('subscribeSocketError',function(e){/** * @event DataFlowLayerViewModel#subscribefailed * @description 数据订阅失败后触发。 * @property {Object} e - 事件对象。 */_this2.fire('subscribefailed',e);});dataService.on('messageSucceeded',function(msg){_this2._addLayer(msg);});this.dataService=dataService;}},{key:"_addLayer",value:function _addLayer(msg){if(!msg.featureResult){return;}var feature=msg.featureResult;var type=feature.geometry.type;var layerStyle=this.layerStyle;if(!this.map.getSource(this.sourceID)){this.map.addSource(this.sourceID,{type:'geojson',data:{type:'FeatureCollection',features:[feature]}});if(type==='Point'){var pointType='circle';var pointPaint={'circle-radius':6,'circle-color':'red'};if(layerStyle.symbol){pointType='symbol';pointPaint={};}this.map.addLayer({id:this.sourceID,type:pointType,source:this.sourceID,paint:layerStyle[pointType]&&layerStyle[pointType].paint||pointPaint,layout:layerStyle[pointType]&&layerStyle[pointType].layout||{}});}else if(type==='MultiPolygon'||type==='Polygon'){this.map.addLayer({id:this.sourceID,type:'fill',paint:layerStyle.fill&&layerStyle.fill.paint||{'fill-color':'red','fill-opacity':1},layout:layerStyle.fill&&layerStyle.fill.layout||{},source:this.sourceID});}else if(type==='LineString'||type==='Line'||type==='MultiLineString'){this.map.addLayer({id:this.sourceID,type:'line',paint:layerStyle.line&&layerStyle.line.paint||{'line-width':5,'line-color':'red','line-opacity':1},layout:layerStyle.line&&layerStyle.line.layout||{},source:this.sourceID});}}else{// update layer var features=(0,_lodash.default)(this.map.getSource(this.sourceID)._data.features);var has=false;features.forEach(function(item,index){if(item.properties.id===feature.properties.id){has=true;features[index]=feature;}});if(!has){features.push(feature);}this.map.getSource(this.sourceID).setData({type:'FeatureCollection',features:features});/** * @event DataFlowLayerViewModel#dataUpdated * @description 数据更新成功后触发。 * @property {GeoJSONObject} data - 更新的数据。 * @property {mapboxgl.Map} map - MapBoxGL Map 对象。 */this.fire('dataupdated',{data:feature,map:this.map});}}}]);return DataFlowLayerViewModel;}(_mapboxGlEnhance.default.Evented);exports["default"]=DataFlowLayerViewModel; /***/ }), /***/ 9183: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var _interopRequireDefault=(__webpack_require__(4836)["default"]);Object.defineProperty(exports, "__esModule", ({value:true}));exports["default"]=void 0;var _classCallCheck2=_interopRequireDefault(__webpack_require__(5671));var _createClass2=_interopRequireDefault(__webpack_require__(3144));var _inherits2=_interopRequireDefault(__webpack_require__(9340));var _createSuper2=_interopRequireDefault(__webpack_require__(8557));var _compose2=_interopRequireDefault(__webpack_require__(8808));var _react=__webpack_require__(3899);var _mapGetter=_interopRequireDefault(__webpack_require__(9635));var _baseLayer=_interopRequireDefault(__webpack_require__(7006));var _DeckglLayerViewModel=_interopRequireDefault(__webpack_require__(5703));var _dec,_class;var LAYER_TYPE_ID_LIST=['scatter-plot','path-layer','polygon-layer','arc-layer','hexagon-layer','screen-grid-layer'];var DeckglLayer=(_dec=(0,_compose2.default)(_mapGetter.default,_baseLayer.default),_dec(_class=/*#__PURE__*/function(_Component){(0,_inherits2.default)(DeckglLayer,_Component);var _super=(0,_createSuper2.default)(DeckglLayer);function DeckglLayer(){(0,_classCallCheck2.default)(this,DeckglLayer);return _super.apply(this,arguments);}(0,_createClass2.default)(DeckglLayer,[{key:"loaded",value:function loaded(map){var _this=this;var matchIndex=LAYER_TYPE_ID_LIST.findIndex(function(item){return item===_this.props.layerType;});if(matchIndex>-1){this.viewModel=new _DeckglLayerViewModel.default(map,this.props);}}},{key:"render",value:function render(){return null;}}]);return DeckglLayer;}(_react.Component))||_class);exports["default"]=DeckglLayer; /***/ }), /***/ 5703: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var _interopRequireDefault=(__webpack_require__(4836)["default"]);Object.defineProperty(exports, "__esModule", ({value:true}));exports["default"]=void 0;var _classCallCheck2=_interopRequireDefault(__webpack_require__(5671));var _createClass2=_interopRequireDefault(__webpack_require__(3144));var _inherits2=_interopRequireDefault(__webpack_require__(9340));var _createSuper2=_interopRequireDefault(__webpack_require__(8557));var _mapboxGlEnhance=_interopRequireDefault(__webpack_require__(375));__webpack_require__(2395);__webpack_require__(2371);var DeckglLayerViewModel=/*#__PURE__*/function(_mapboxgl$Evented){(0,_inherits2.default)(DeckglLayerViewModel,_mapboxgl$Evented);var _super=(0,_createSuper2.default)(DeckglLayerViewModel);function DeckglLayerViewModel(map,deckglProps){var _this;(0,_classCallCheck2.default)(this,DeckglLayerViewModel);_this=_super.call(this);_this.map=map;var layerType=deckglProps.layerType,options=deckglProps.options,layerId=deckglProps.layerId;_this.layerType=layerType;options.data=options.data||[];options.layerId=options.layerId||layerId;_this.options=options;_this._init();return _this;}(0,_createClass2.default)(DeckglLayerViewModel,[{key:"_init",value:function _init(){if(this.layerType&&this.options){this._addDeckglLayer();}}},{key:"_addDeckglLayer",value:function _addDeckglLayer(){var deckglLayer=new _mapboxGlEnhance.default.supermap.DeckglLayer(this.layerType,this.options);this.map.addLayer(deckglLayer);}}]);return DeckglLayerViewModel;}(_mapboxGlEnhance.default.Evented);exports["default"]=DeckglLayerViewModel; /***/ }), /***/ 1762: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var _interopRequireDefault=(__webpack_require__(4836)["default"]);Object.defineProperty(exports, "__esModule", ({value:true}));exports["default"]=void 0;var _classCallCheck2=_interopRequireDefault(__webpack_require__(5671));var _createClass2=_interopRequireDefault(__webpack_require__(3144));var _inherits2=_interopRequireDefault(__webpack_require__(9340));var _createSuper2=_interopRequireDefault(__webpack_require__(8557));var _compose2=_interopRequireDefault(__webpack_require__(8808));var _react=_interopRequireDefault(__webpack_require__(3899));var _mapGetter=_interopRequireDefault(__webpack_require__(9635));var _baseLayer=_interopRequireDefault(__webpack_require__(7006));var _EchatsLayerViewModel=_interopRequireDefault(__webpack_require__(3395));var _dec,_class;var EchartsLayer=(_dec=(0,_compose2.default)(_mapGetter.default,_baseLayer.default),_dec(_class=/*#__PURE__*/function(_React$Component){(0,_inherits2.default)(EchartsLayer,_React$Component);var _super=(0,_createSuper2.default)(EchartsLayer);function EchartsLayer(){(0,_classCallCheck2.default)(this,EchartsLayer);return _super.apply(this,arguments);}(0,_createClass2.default)(EchartsLayer,[{key:"loaded",value:function loaded(map){this.viewModel=new _EchatsLayerViewModel.default(map,this.props.options);}},{key:"render",value:function render(){return null;}}]);return EchartsLayer;}(_react.default.Component))||_class);exports["default"]=EchartsLayer; /***/ }), /***/ 3395: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var _interopRequireDefault=(__webpack_require__(4836)["default"]);Object.defineProperty(exports, "__esModule", ({value:true}));exports["default"]=void 0;var _classCallCheck2=_interopRequireDefault(__webpack_require__(5671));var _createClass2=_interopRequireDefault(__webpack_require__(3144));var _inherits2=_interopRequireDefault(__webpack_require__(9340));var _createSuper2=_interopRequireDefault(__webpack_require__(8557));var _echarts=_interopRequireDefault(__webpack_require__(550));var _mapboxGlEnhance=_interopRequireDefault(__webpack_require__(375));var _EchartsLayer=_interopRequireDefault(__webpack_require__(3094));/** * @class EchatsLayerViewModel * @param {mapboxgl.map} map - mapboxgl map 对象。 * @param {String} options - EchartsLayer options。 */var EchatsLayerViewModel=/*#__PURE__*/function(_mapboxgl$Evented){(0,_inherits2.default)(EchatsLayerViewModel,_mapboxgl$Evented);var _super=(0,_createSuper2.default)(EchatsLayerViewModel);function EchatsLayerViewModel(map,options){var _this;(0,_classCallCheck2.default)(this,EchatsLayerViewModel);_this=_super.call(this);if(!options){throw new Error('echarts options is requierd');}if(!map){throw new Error('map is requierd');}_this.map=map;_this.options=options;_this._initializeEchartsLayer();return _this;}(0,_createClass2.default)(EchatsLayerViewModel,[{key:"_initializeEchartsLayer",value:function _initializeEchartsLayer(){window.echarts=_echarts.default;var echartslayer=new _EchartsLayer.default(this.map);echartslayer.chart.setOption(this.options);/** * @event echartslayeraddsucceeded * @property {Object} layer - Echarts Layer. */this.fire('echartslayeraddsucceeded',{layer:echartslayer});this.echartslayer=echartslayer;}}]);return EchatsLayerViewModel;}(_mapboxGlEnhance.default.Evented);exports["default"]=EchatsLayerViewModel; /***/ }), /***/ 4799: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var _interopRequireDefault=(__webpack_require__(4836)["default"]);Object.defineProperty(exports, "__esModule", ({value:true}));exports["default"]=void 0;var _classCallCheck2=_interopRequireDefault(__webpack_require__(5671));var _createClass2=_interopRequireDefault(__webpack_require__(3144));var _inherits2=_interopRequireDefault(__webpack_require__(9340));var _createSuper2=_interopRequireDefault(__webpack_require__(8557));var _compose2=_interopRequireDefault(__webpack_require__(8808));var _react=_interopRequireDefault(__webpack_require__(3899));var _lodash=_interopRequireDefault(__webpack_require__(2307));var _mapGetter=_interopRequireDefault(__webpack_require__(9635));var _baseLayer=_interopRequireDefault(__webpack_require__(7006));var _FireLayerViewModel=_interopRequireDefault(__webpack_require__(5382));var _dec,_class,_class2;var FireLayer=(_dec=(0,_compose2.default)(_mapGetter.default,_baseLayer.default),_dec(_class=(_class2=/*#__PURE__*/function(_React$Component){(0,_inherits2.default)(FireLayer,_React$Component);var _super=(0,_createSuper2.default)(FireLayer);function FireLayer(){(0,_classCallCheck2.default)(this,FireLayer);return _super.apply(this,arguments);}(0,_createClass2.default)(FireLayer,[{key:"componentDidUpdate",value:function componentDidUpdate(prevProps){var _this$props=this.props,features=_this$props.features,modelScale=_this$props.modelScale;if(this.viewModel){if(!(0,_lodash.default)(prevProps.features,features)){this.viewModel.setFeatures(features);}if(prevProps.modelScale!==modelScale){this.viewModel.setModelScale(modelScale);}}}},{key:"loaded",value:function loaded(map){this.viewModel=new _FireLayerViewModel.default(map,this.props.features,this.props.modelScale,this.props.layerId);}},{key:"render",value:function render(){return null;}}]);return FireLayer;}(_react.default.Component),_class2.defaultProps={modelScale:5.41843220338983e-6},_class2))||_class);exports["default"]=FireLayer; /***/ }), /***/ 5382: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var _interopRequireWildcard=(__webpack_require__(5263)["default"]);var _interopRequireDefault=(__webpack_require__(4836)["default"]);Object.defineProperty(exports, "__esModule", ({value:true}));exports["default"]=void 0;var _toConsumableArray2=_interopRequireDefault(__webpack_require__(2982));var _classCallCheck2=_interopRequireDefault(__webpack_require__(5671));var _createClass2=_interopRequireDefault(__webpack_require__(3144));var _inherits2=_interopRequireDefault(__webpack_require__(9340));var _createSuper2=_interopRequireDefault(__webpack_require__(8557));var THREE=_interopRequireWildcard(__webpack_require__(2069));var _mapboxGlEnhance=_interopRequireDefault(__webpack_require__(375));var _tendrils=_interopRequireDefault(__webpack_require__(2769));/** * @class FireLayerViewModel * @param {mapboxgl.map} map - mapboxgl map 对象。 */var FireLayerViewModel=/*#__PURE__*/function(_mapboxgl$Evented){(0,_inherits2.default)(FireLayerViewModel,_mapboxgl$Evented);var _super=(0,_createSuper2.default)(FireLayerViewModel);function FireLayerViewModel(map,features){var _this;var modelScale=arguments.length>2&&arguments[2]!==undefined?arguments[2]:5.41843220338983e-6;var layerId=arguments.length>3?arguments[3]:undefined;(0,_classCallCheck2.default)(this,FireLayerViewModel);_this=_super.call(this);if(!map){throw new Error('map is requierd');}_this.map=map;_this.layerId=layerId;_this.features=features;_this.modelScale=modelScale;_this.features&&_this._addFireLayer();return _this;}(0,_createClass2.default)(FireLayerViewModel,[{key:"setFeatures",value:function setFeatures(features){this.features=features;this._addFireLayer();}},{key:"setModelScale",value:function setModelScale(modelScale){this.modelScale=modelScale;this._addFireLayer();}},{key:"_addFireLayer",value:function _addFireLayer(){var _this2=this;var feature=this.features.features[0];if(feature.geometry.type!=='Point'){throw new Error("Feature's type must be point");}if(this.features.features.length>50){throw new Error('The maximum number of features is 50');}this.features.features.forEach(function(feature,index){var geometry=feature.geometry;if(geometry.type==='Point'){_this2._initializeFireLayer(geometry.coordinates,index);}});}},{key:"_initializeFireLayer",value:function _initializeFireLayer(originCoordinate,index){var _this3=this;var modelTransform=this._getModelTransform(originCoordinate);var layerId=this.layerId&&this.layerId+'-'+index||"threeLayerFire-".concat(new Date());this.map.getLayer(layerId)&&this.map.removeLayer(layerId);var customLayer={id:layerId,type:'custom',renderingMode:'3d',onAdd:function onAdd(map,gl){_this3.camera=new THREE.PerspectiveCamera(45,map.getCanvas().width/map.getCanvas().height,0.1,2000);_this3.scene=new THREE.Scene();_this3.renderer=new THREE.WebGLRenderer({canvas:map.getCanvas(),context:gl,antialias:true});_this3.renderer.autoClear=false;var rig=new THREE.Group();rig.add(_this3.camera);_this3.scene.add(rig);_this3._fire();_this3.scene.add(_this3._object);var light=new THREE.PointLight(0xffffff,1,100);light.position.set(10,10,20);_this3.scene.add(light);_this3.map=map;},render:function render(gl,matrix){var rotationX=new THREE.Matrix4().makeRotationAxis(new THREE.Vector3(1,0,0),modelTransform.rotateX);var rotationY=new THREE.Matrix4().makeRotationAxis(new THREE.Vector3(0,1,0),modelTransform.rotateY);var rotationZ=new THREE.Matrix4().makeRotationAxis(new THREE.Vector3(0,0,1),modelTransform.rotateZ);var m=new THREE.Matrix4().fromArray(matrix);var l=new THREE.Matrix4().makeTranslation(modelTransform.translateX,modelTransform.translateY,modelTransform.translateZ).scale(new THREE.Vector3(modelTransform.scale,-modelTransform.scale,modelTransform.scale)).multiply(rotationX).multiply(rotationY).multiply(rotationZ);_this3.camera.projectionMatrix.elements=matrix;_this3.camera.projectionMatrix=m.multiply(l);_this3.renderer.state.reset();_this3._update();_this3.renderer.render(_this3.scene,_this3.camera);// @ts-ignore _this3.map.triggerRepaint();}};// @ts-ignore TODO mapbox-gl types 未更新 this.map.addLayer(customLayer);}},{key:"_getModelTransform",value:function _getModelTransform(originCoordinate){var modelOrigin=originCoordinate;var modelAltitude=0;var modelRotate=[Math.PI/2,0,0];var modelTransform={translateX:_mapboxGlEnhance.default.MercatorCoordinate.fromLngLat(modelOrigin,modelAltitude).x,translateY:_mapboxGlEnhance.default.MercatorCoordinate.fromLngLat(modelOrigin,modelAltitude).y,translateZ:_mapboxGlEnhance.default.MercatorCoordinate.fromLngLat(modelOrigin,modelAltitude).z,rotateX:modelRotate[0],rotateY:modelRotate[1],rotateZ:modelRotate[2],scale:this.modelScale};return modelTransform;}},{key:"_fire",value:function _fire(){var _this$_object;var density=arguments.length>0&&arguments[0]!==undefined?arguments[0]:150;var height=arguments.length>1&&arguments[1]!==undefined?arguments[1]:8;var r=arguments.length>2&&arguments[2]!==undefined?arguments[2]:0.2;this._object=new THREE.Group();this._fireballs=[];this._height=height;this._radius=r;var texture=new THREE.TextureLoader().load(_tendrils.default,function(){console.log('loaded');},undefined,function(e){console.log('error',e);});// @ts-ignore texture.crossOrigin='';// "anonymous"; this._fireMaterial=new THREE.ShaderMaterial({uniforms:{time:{value:1.0},blend:{value:1.0},blendPattern:{type:'t',value:texture}},vertexShader:"precision mediump float;\n precision mediump int;\n attribute vec4 color;\n varying vec2 vUv;\n varying float vFade;\n void main()\t{\n vUv = uv;\n vec4 localPosition = vec4( position, 1);\n vFade = clamp((localPosition.y + 3.0) / 6.0, 0.0, 1.0);\n gl_Position = projectionMatrix * modelViewMatrix * localPosition;\n }",fragmentShader:"precision mediump float;\n precision mediump int;\n uniform float time;\n uniform float blend;\n uniform sampler2D blendPattern;\n varying float vFade;\n varying vec2 vUv;\n\n\n void main()\t{\n\n vec4 startColor = vec4(1., 0.5, 0.1, 1.0);\n vec4 endColor = vec4(0.2, 0.2, 0.2, 1.0);\n\n float dissolve = texture2D(blendPattern, vUv).r * 0.5;\n\n float spread = 0.4;\n\n float fadeAmount = smoothstep(\n max(0.0, vFade - spread),\n min(1.0, vFade + spread),\n blend + dissolve\n );\n\n vec4 color = mix(\n startColor, endColor,\n smoothstep(0.1,1., fadeAmount)\n );\n\n gl_FragColor = vec4(color.rgb, 1.-fadeAmount);\n }",transparent:true,side:THREE.DoubleSide,blending:THREE.AdditiveBlending});this._light=new THREE.PointLight(0xff5500,1,100);this._light.position.set(0,0.4,0);this._lightIntensity=Math.random()*5;this._object.add(this._light);// this._fireMaterial = new THREE.MeshStandardMaterial(0x661100); for(var i=0;i_this4._height){ball.position.y=Math.random()*0.1;ball.position.x=(0.5-Math.random())*_this4._radius;ball.position.z=(0.5-Math.random())*_this4._radius;}var p=0.1+ball.position.y/_this4._height;ball.rotateX((1.2-p)*0.01);ball.rotateZ((1.2-p)*0.01);ball.rotateY((1.2-p)*0.01);ball.scale.set(p,p,p);/// ball.opacity = p; ball.material.uniforms.blend.value=p;// ball.material.needsUpdate = true; });this._light.intensity+=(this._lightIntensity-this._light.intensity)*0.006;if(Math.random()>0.8){this._lightIntensity=Math.random()*5;}}}]);return FireLayerViewModel;}(_mapboxGlEnhance.default.Evented);exports["default"]=FireLayerViewModel; /***/ }), /***/ 9704: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var _interopRequireDefault=(__webpack_require__(4836)["default"]);Object.defineProperty(exports, "__esModule", ({value:true}));exports["default"]=void 0;var _classCallCheck2=_interopRequireDefault(__webpack_require__(5671));var _createClass2=_interopRequireDefault(__webpack_require__(3144));var _inherits2=_interopRequireDefault(__webpack_require__(9340));var _createSuper2=_interopRequireDefault(__webpack_require__(8557));var _compose2=_interopRequireDefault(__webpack_require__(8808));var _react=__webpack_require__(3899);var _GeojsonLayerViewModel=_interopRequireDefault(__webpack_require__(8428));var _lodash=_interopRequireDefault(__webpack_require__(2307));var _mapGetter=_interopRequireDefault(__webpack_require__(9635));var _baseLayer=_interopRequireDefault(__webpack_require__(7006));var _dec,_class;var GeojsonLayer=(_dec=(0,_compose2.default)(_mapGetter.default,_baseLayer.default),_dec(_class=/*#__PURE__*/function(_Component){(0,_inherits2.default)(GeojsonLayer,_Component);var _super=(0,_createSuper2.default)(GeojsonLayer);function GeojsonLayer(){(0,_classCallCheck2.default)(this,GeojsonLayer);return _super.apply(this,arguments);}(0,_createClass2.default)(GeojsonLayer,[{key:"componentDidUpdate",value:function componentDidUpdate(prevProps){if(!(0,_lodash.default)(this.props.layerStyle,prevProps.layerStyle)&&this.viewModel){this.viewModel.setLayerStyle(this.props.layerStyle);}if(!(0,_lodash.default)(this.props.data,prevProps.data)&&this.viewModel){this.viewModel.setData(this.props.data);}}},{key:"loaded",value:function loaded(map){this.viewModel=new _GeojsonLayerViewModel.default(map,this.props);}},{key:"render",value:function render(){return null;}}]);return GeojsonLayer;}(_react.Component))||_class);exports["default"]=GeojsonLayer; /***/ }), /***/ 8428: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var _interopRequireDefault=(__webpack_require__(4836)["default"]);Object.defineProperty(exports, "__esModule", ({value:true}));exports["default"]=void 0;var _classCallCheck2=_interopRequireDefault(__webpack_require__(5671));var _createClass2=_interopRequireDefault(__webpack_require__(3144));var _inherits2=_interopRequireDefault(__webpack_require__(9340));var _createSuper2=_interopRequireDefault(__webpack_require__(8557));var _mapboxGlEnhance=_interopRequireDefault(__webpack_require__(375));var GeojsonLayerViewModel=/*#__PURE__*/function(_mapboxgl$Evented){(0,_inherits2.default)(GeojsonLayerViewModel,_mapboxgl$Evented);var _super=(0,_createSuper2.default)(GeojsonLayerViewModel);function GeojsonLayerViewModel(map,GeojsonLayerOptions){var _this;(0,_classCallCheck2.default)(this,GeojsonLayerViewModel);_this=_super.call(this);if(!map){throw new Error('map is requierd');}_this.map=map;var layerStyle=GeojsonLayerOptions.layerStyle,data=GeojsonLayerOptions.data,layerId=GeojsonLayerOptions.layerId;_this.data=data;_this.layerStyle=layerStyle;_this.layerId=layerId;_this.data&&_this._addLayer();return _this;}(0,_createClass2.default)(GeojsonLayerViewModel,[{key:"setData",value:function setData(data){if(!data||!this.map.getSource(this.layerId)){return;}this.data=data;if(this.layerId&&!this.map.getSource(this.layerId)){this._addLayer();}else{this.map.getSource(this.layerId).setData(data);}}},{key:"setLayerStyle",value:function setLayerStyle(layerStyle){if(!layerStyle||!this.map.getSource(this.layerId)){return;}var paint=layerStyle.paint,layout=layerStyle.layout;for(var _i=0,_Object$keys=Object.keys(paint);_i<_Object$keys.length;_i++){var prop=_Object$keys[_i];this.map.setPaintProperty(this.layerId,prop,paint[prop]);}for(var _i2=0,_Object$keys2=Object.keys(layout);_i2<_Object$keys2.length;_i2++){var _prop=_Object$keys2[_i2];this.map.setLayoutProperty(this.layerId,_prop,layout[_prop]);}this.layerStyle=layerStyle;}},{key:"_addLayer",value:function _addLayer(){if(!(this.layerStyle instanceof Object))throw new Error('layerStyle must be object');var _this$layerStyle=this.layerStyle,paint=_this$layerStyle.paint,layout=_this$layerStyle.layout;this.map.addLayer({id:this.layerId,type:this._getLayerType(paint),source:{type:'geojson',data:this.data},layout:layout||{},paint:paint||{}});}},{key:"_getLayerType",value:function _getLayerType(){var paint=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{};var keys=Object.keys(paint).join(' ');var reg=/circle-|line-|fill-extrusion-|fill-+/i;var matchType=keys.match(reg);var type=matchType?matchType[0]:'';return type.substr(0,type.length-1);}}]);return GeojsonLayerViewModel;}(_mapboxGlEnhance.default.Evented);exports["default"]=GeojsonLayerViewModel; /***/ }), /***/ 910: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var _interopRequireDefault=(__webpack_require__(4836)["default"]);Object.defineProperty(exports, "__esModule", ({value:true}));exports["default"]=void 0;var _classCallCheck2=_interopRequireDefault(__webpack_require__(5671));var _createClass2=_interopRequireDefault(__webpack_require__(3144));var _inherits2=_interopRequireDefault(__webpack_require__(9340));var _createSuper2=_interopRequireDefault(__webpack_require__(8557));var _compose2=_interopRequireDefault(__webpack_require__(8808));var _react=_interopRequireDefault(__webpack_require__(3899));var _lodash=_interopRequireDefault(__webpack_require__(2307));var _mapGetter=_interopRequireDefault(__webpack_require__(9635));var _baseLayer=_interopRequireDefault(__webpack_require__(7006));var _util=__webpack_require__(9752);var _GraphThemeLayerViewModel=_interopRequireDefault(__webpack_require__(1043));var _dec,_class,_class2;var GraphThemeLayer=(_dec=(0,_compose2.default)(_mapGetter.default,_baseLayer.default),_dec(_class=(_class2=/*#__PURE__*/function(_React$Component){(0,_inherits2.default)(GraphThemeLayer,_React$Component);var _super=(0,_createSuper2.default)(GraphThemeLayer);function GraphThemeLayer(){(0,_classCallCheck2.default)(this,GraphThemeLayer);return _super.apply(this,arguments);}(0,_createClass2.default)(GraphThemeLayer,[{key:"componentDidUpdate",value:function componentDidUpdate(prevProps){var data=this.props.data;if(!(0,_lodash.default)(prevProps.data,data)&&this.viewModel){this.viewModel.setData(data);}}},{key:"loaded",value:function loaded(map){var onLoad=this.props.onLoad;this.viewModel=new _GraphThemeLayerViewModel.default(map,this.props);(0,_util.isFunction)(onLoad)&&onLoad(this.viewModel.themeLayer,map);}},{key:"render",value:function render(){return null;}}]);return GraphThemeLayer;}(_react.default.Component),_class2.defaultProps={options:{},chartsType:'Bar'},_class2))||_class);exports["default"]=GraphThemeLayer; /***/ }), /***/ 1043: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var _interopRequireDefault=(__webpack_require__(4836)["default"]);Object.defineProperty(exports, "__esModule", ({value:true}));exports["default"]=void 0;var _classCallCheck2=_interopRequireDefault(__webpack_require__(5671));var _createClass2=_interopRequireDefault(__webpack_require__(3144));var _inherits2=_interopRequireDefault(__webpack_require__(9340));var _createSuper2=_interopRequireDefault(__webpack_require__(8557));var _mapboxGlEnhance=_interopRequireDefault(__webpack_require__(375));__webpack_require__(2395);var GraphThemeLayerViewModel=/*#__PURE__*/function(_mapboxgl$Evented){(0,_inherits2.default)(GraphThemeLayerViewModel,_mapboxgl$Evented);var _super=(0,_createSuper2.default)(GraphThemeLayerViewModel);function GraphThemeLayerViewModel(map,themeProps){var _this;(0,_classCallCheck2.default)(this,GraphThemeLayerViewModel);_this=_super.call(this);_this.map=map;var layerName=themeProps.layerName,options=themeProps.options,chartsType=themeProps.chartsType,layerId=themeProps.layerId,data=themeProps.data;_this.layerName=layerName||layerId;_this.chartsType=chartsType||'Bar';options.id=options.id||layerId;_this.options=options;_this.data=data||{};_this._init();return _this;}(0,_createClass2.default)(GraphThemeLayerViewModel,[{key:"_init",value:function _init(){this.themeLayer=new _mapboxGlEnhance.default.supermap.GraphThemeLayer(this.layerName,this.chartsType,this.options);this.map.addLayer(this.themeLayer);if(JSON.stringify(this.data)!=='{}'){this.setData(this.data);}}},{key:"setData",value:function setData(data){this.themeLayer.addFeatures(data);}}]);return GraphThemeLayerViewModel;}(_mapboxGlEnhance.default.Evented);exports["default"]=GraphThemeLayerViewModel; /***/ }), /***/ 6073: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var _interopRequireDefault=(__webpack_require__(4836)["default"]);Object.defineProperty(exports, "__esModule", ({value:true}));exports["default"]=void 0;var _classCallCheck2=_interopRequireDefault(__webpack_require__(5671));var _createClass2=_interopRequireDefault(__webpack_require__(3144));var _inherits2=_interopRequireDefault(__webpack_require__(9340));var _createSuper2=_interopRequireDefault(__webpack_require__(8557));var _compose2=_interopRequireDefault(__webpack_require__(8808));var _react=_interopRequireDefault(__webpack_require__(3899));var _lodash=_interopRequireDefault(__webpack_require__(2307));var _mapGetter=_interopRequireDefault(__webpack_require__(9635));var _baseLayer=_interopRequireDefault(__webpack_require__(7006));var _HeatmapLayerViewModel=_interopRequireDefault(__webpack_require__(9354));var _HeatMapStyle=_interopRequireDefault(__webpack_require__(9623));var _dec,_class,_class2;var HeatmapLayer=(_dec=(0,_compose2.default)(_mapGetter.default,_baseLayer.default),_dec(_class=(_class2=/*#__PURE__*/function(_React$Component){(0,_inherits2.default)(HeatmapLayer,_React$Component);var _super=(0,_createSuper2.default)(HeatmapLayer);function HeatmapLayer(){(0,_classCallCheck2.default)(this,HeatmapLayer);return _super.apply(this,arguments);}(0,_createClass2.default)(HeatmapLayer,[{key:"componentDidUpdate",value:function componentDidUpdate(prevProps){if(prevProps.layerStyle!==this.props.layerStyle){this.viewModel&&this.viewModel.setLayerStyle(this.props.layerStyle);}if(!(0,_lodash.default)(this.props.data,prevProps.data)&&this.viewModel){this.viewModel.setData(this.props.data);}}},{key:"loaded",value:function loaded(map){var _this$props=this.props,data=_this$props.data,layerId=_this$props.layerId,layerStyle=_this$props.layerStyle;this.viewModel=new _HeatmapLayerViewModel.default(map,data,{layerId:layerId,layerStyle:layerStyle});}},{key:"render",value:function render(){return null;}}]);return HeatmapLayer;}(_react.default.Component),_class2.defaultProps={layerStyle:new _HeatMapStyle.default()},_class2))||_class);exports["default"]=HeatmapLayer; /***/ }), /***/ 9354: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var _interopRequireDefault=(__webpack_require__(4836)["default"]);Object.defineProperty(exports, "__esModule", ({value:true}));exports["default"]=void 0;var _classCallCheck2=_interopRequireDefault(__webpack_require__(5671));var _createClass2=_interopRequireDefault(__webpack_require__(3144));var _inherits2=_interopRequireDefault(__webpack_require__(9340));var _createSuper2=_interopRequireDefault(__webpack_require__(8557));var _mapboxGlEnhance=_interopRequireDefault(__webpack_require__(375));/** * @class HeatMapLayerViewModel * @param {mapboxgl.map} map - mapboxgl map 对象。 * @param {String} data - 热力图数据。 * @param {Object} options - 可选参数。 * @param {Object} [options.layerId] - 图层名。 * @param {Object} [options.layerStyle] - 图层样式配置。 */var HeatMapLayerViewModel=/*#__PURE__*/function(_mapboxgl$Evented){(0,_inherits2.default)(HeatMapLayerViewModel,_mapboxgl$Evented);var _super=(0,_createSuper2.default)(HeatMapLayerViewModel);function HeatMapLayerViewModel(map,data,options){var _this;(0,_classCallCheck2.default)(this,HeatMapLayerViewModel);_this=_super.call(this);if(!map){throw new Error('map is requierd');}options=options||{};_this.map=map;_this.data=data;_this.layerId=options.layerId||'heatmap'+new Date().getTime();var layerStyle=options.layerStyle;_this.paint=layerStyle&&layerStyle.paint;_this.layout=layerStyle&&layerStyle.layout;_this._initializeHeatMapLayer();return _this;}(0,_createClass2.default)(HeatMapLayerViewModel,[{key:"setData",value:function setData(data){if(!data||!this.map.getSource(this.layerId)){return;}this.data=data;if(this.layerId&&!this.map.getSource(this.layerId)){this._initializeHeatMapLayer();}else{this.map.getSource(this.layerId).setData(data);}}},{key:"setLayerStyle",value:function setLayerStyle(layerStyle){if(!layerStyle||!this.map.getSource(this.layerId)){return;}var paint=layerStyle.paint,layout=layerStyle.layout;for(var _i=0,_Object$keys=Object.keys(paint);_i<_Object$keys.length;_i++){var prop=_Object$keys[_i];this.map.setPaintProperty(this.layerId,prop,paint[prop]);}for(var _i2=0,_Object$keys2=Object.keys(layout);_i2<_Object$keys2.length;_i2++){var _prop=_Object$keys2[_i2];this.map.setLayoutProperty(this.layerId,_prop,layout[_prop]);}this.layerStyle=layerStyle;}},{key:"_initializeHeatMapLayer",value:function _initializeHeatMapLayer(){this.map.addSource(this.layerId,{type:'geojson',data:this.data});this.map.addLayer({id:this.layerId,type:'heatmap',source:this.layerId,paint:this.paint||{'heatmap-intensity':['interpolate',['linear'],['zoom'],0,1,9,3],'heatmap-color':['interpolate',['linear'],['heatmap-density'],0,'rgba(33,102,172,0)',0.2,'rgb(103,169,207)',0.4,'rgb(209,229,240)',0.6,'rgb(253,219,199)',0.8,'rgb(239,138,98)',1,'rgb(178,24,43)'],'heatmap-radius':['interpolate',['linear'],['zoom'],0,2,9,20]},layout:this.layout||{}});this.fire('heatmaplayeraddsucceeded',{map:this.map});}}]);return HeatMapLayerViewModel;}(_mapboxGlEnhance.default.Evented);exports["default"]=HeatMapLayerViewModel; /***/ }), /***/ 2174: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var _interopRequireDefault=(__webpack_require__(4836)["default"]);Object.defineProperty(exports, "__esModule", ({value:true}));exports["default"]=void 0;var _classCallCheck2=_interopRequireDefault(__webpack_require__(5671));var _createClass2=_interopRequireDefault(__webpack_require__(3144));var _inherits2=_interopRequireDefault(__webpack_require__(9340));var _createSuper2=_interopRequireDefault(__webpack_require__(8557));var _compose2=_interopRequireDefault(__webpack_require__(8808));var _react=__webpack_require__(3899);var _mapGetter=_interopRequireDefault(__webpack_require__(9635));var _baseLayer=_interopRequireDefault(__webpack_require__(7006));var _util=__webpack_require__(9752);var _LabelThemeLayerViewModel=_interopRequireDefault(__webpack_require__(8499));var _dec,_class,_class2;var LabelThemeLayer=(_dec=(0,_compose2.default)(_mapGetter.default,_baseLayer.default),_dec(_class=(_class2=/*#__PURE__*/function(_Component){(0,_inherits2.default)(LabelThemeLayer,_Component);var _super=(0,_createSuper2.default)(LabelThemeLayer);function LabelThemeLayer(){(0,_classCallCheck2.default)(this,LabelThemeLayer);return _super.apply(this,arguments);}(0,_createClass2.default)(LabelThemeLayer,[{key:"loaded",value:function loaded(map){var onLoad=this.props.onLoad;this.viewModel=new _LabelThemeLayerViewModel.default(map,this.props);(0,_util.isFunction)(onLoad)&&onLoad(this.viewModel.themeLayer,map);}},{key:"render",value:function render(){return null;}}]);return LabelThemeLayer;}(_react.Component),_class2.defaultProps={options:{}},_class2))||_class);exports["default"]=LabelThemeLayer; /***/ }), /***/ 8499: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var _interopRequireDefault=(__webpack_require__(4836)["default"]);Object.defineProperty(exports, "__esModule", ({value:true}));exports["default"]=void 0;var _classCallCheck2=_interopRequireDefault(__webpack_require__(5671));var _createClass2=_interopRequireDefault(__webpack_require__(3144));var _inherits2=_interopRequireDefault(__webpack_require__(9340));var _createSuper2=_interopRequireDefault(__webpack_require__(8557));var _mapboxGlEnhance=_interopRequireDefault(__webpack_require__(375));__webpack_require__(2395);var LabelThemeLayerViewModel=/*#__PURE__*/function(_mapboxgl$Evented){(0,_inherits2.default)(LabelThemeLayerViewModel,_mapboxgl$Evented);var _super=(0,_createSuper2.default)(LabelThemeLayerViewModel);function LabelThemeLayerViewModel(map,themeProps){var _this;(0,_classCallCheck2.default)(this,LabelThemeLayerViewModel);_this=_super.call(this);var layerName=themeProps.layerName,options=themeProps.options,layerId=themeProps.layerId,data=themeProps.data;_this.map=map;_this.layerName=layerName||layerId;options.id=options.id||layerId;_this.options=options;_this.data=data||[];_this._init();return _this;}(0,_createClass2.default)(LabelThemeLayerViewModel,[{key:"_init",value:function _init(){this.themeLayer=new _mapboxGlEnhance.default.supermap.LabelThemeLayer(this.layerName,this.options);this.map.addLayer(this.themeLayer);this.themeLayer.addFeatures(this.data);}}]);return LabelThemeLayerViewModel;}(_mapboxGlEnhance.default.Evented);exports["default"]=LabelThemeLayerViewModel; /***/ }), /***/ 7: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var _interopRequireDefault=(__webpack_require__(4836)["default"]);Object.defineProperty(exports, "__esModule", ({value:true}));exports["default"]=void 0;var _classCallCheck2=_interopRequireDefault(__webpack_require__(5671));var _createClass2=_interopRequireDefault(__webpack_require__(3144));var _inherits2=_interopRequireDefault(__webpack_require__(9340));var _createSuper2=_interopRequireDefault(__webpack_require__(8557));var _compose2=_interopRequireDefault(__webpack_require__(8808));var _react=_interopRequireDefault(__webpack_require__(3899));var _mapGetter=_interopRequireDefault(__webpack_require__(9635));var _baseLayer=_interopRequireDefault(__webpack_require__(7006));var _MapvLayerViewModel=_interopRequireDefault(__webpack_require__(8862));var _dec,_class,_class2;var MapvLayer=(_dec=(0,_compose2.default)(_mapGetter.default,_baseLayer.default),_dec(_class=(_class2=/*#__PURE__*/function(_React$Component){(0,_inherits2.default)(MapvLayer,_React$Component);var _super=(0,_createSuper2.default)(MapvLayer);function MapvLayer(){(0,_classCallCheck2.default)(this,MapvLayer);return _super.apply(this,arguments);}(0,_createClass2.default)(MapvLayer,[{key:"loaded",value:function loaded(map){this.viewModel=new _MapvLayerViewModel.default(map,this.props);}},{key:"render",value:function render(){return null;}}]);return MapvLayer;}(_react.default.Component),_class2.defaultProps={options:{},data:{}},_class2))||_class);exports["default"]=MapvLayer; /***/ }), /***/ 8862: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var _interopRequireDefault=(__webpack_require__(4836)["default"]);Object.defineProperty(exports, "__esModule", ({value:true}));exports["default"]=void 0;var _objectSpread2=_interopRequireDefault(__webpack_require__(8683));var _classCallCheck2=_interopRequireDefault(__webpack_require__(5671));var _createClass2=_interopRequireDefault(__webpack_require__(3144));var _inherits2=_interopRequireDefault(__webpack_require__(9340));var _createSuper2=_interopRequireDefault(__webpack_require__(8557));var _mapboxGlEnhance=_interopRequireDefault(__webpack_require__(375));__webpack_require__(2395);var MapvLayerViewModel=/*#__PURE__*/function(_mapboxgl$Evented){(0,_inherits2.default)(MapvLayerViewModel,_mapboxgl$Evented);var _super=(0,_createSuper2.default)(MapvLayerViewModel);function MapvLayerViewModel(map,mapvLayerProps){var _this;(0,_classCallCheck2.default)(this,MapvLayerViewModel);_this=_super.call(this);_this.map=map;var data=mapvLayerProps.data,options=mapvLayerProps.options,layerId=mapvLayerProps.layerId;_this.data=data;_this.options=options.layerId?options:(0,_objectSpread2.default)((0,_objectSpread2.default)({},options),{},{layerId:layerId});_this._init();return _this;}(0,_createClass2.default)(MapvLayerViewModel,[{key:"_init",value:function _init(){if(this.data&&this.options){this._addMapvLayer();}}},{key:"_addMapvLayer",value:function _addMapvLayer(){var mapVLayer=new _mapboxGlEnhance.default.supermap.MapvLayer('',this.data,this.options);this.map.addLayer(mapVLayer);}}]);return MapvLayerViewModel;}(_mapboxGlEnhance.default.Evented);exports["default"]=MapvLayerViewModel; /***/ }), /***/ 5890: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var _interopRequireDefault=(__webpack_require__(4836)["default"]);Object.defineProperty(exports, "__esModule", ({value:true}));exports["default"]=void 0;var _classCallCheck2=_interopRequireDefault(__webpack_require__(5671));var _createClass2=_interopRequireDefault(__webpack_require__(3144));var _inherits2=_interopRequireDefault(__webpack_require__(9340));var _createSuper2=_interopRequireDefault(__webpack_require__(8557));var _compose2=_interopRequireDefault(__webpack_require__(8808));var _react=_interopRequireDefault(__webpack_require__(3899));var _lodash=_interopRequireDefault(__webpack_require__(2307));var _mapGetter=_interopRequireDefault(__webpack_require__(9635));var _baseLayer=_interopRequireDefault(__webpack_require__(7006));var _util=__webpack_require__(9752);var _RangeThemeLayerViewModel=_interopRequireDefault(__webpack_require__(5040));var _dec,_class,_class2;var RangeThemeLayer=(_dec=(0,_compose2.default)(_mapGetter.default,_baseLayer.default),_dec(_class=(_class2=/*#__PURE__*/function(_React$Component){(0,_inherits2.default)(RangeThemeLayer,_React$Component);var _super=(0,_createSuper2.default)(RangeThemeLayer);function RangeThemeLayer(){(0,_classCallCheck2.default)(this,RangeThemeLayer);return _super.apply(this,arguments);}(0,_createClass2.default)(RangeThemeLayer,[{key:"componentDidUpdate",value:function componentDidUpdate(prevProps){var data=this.props.data;if(!(0,_lodash.default)(prevProps.data,data)&&this.viewModel){this.viewModel.setData(data);}}},{key:"loaded",value:function loaded(map){var onLoad=this.props.onLoad;this.viewModel=new _RangeThemeLayerViewModel.default(map,this.props);(0,_util.isFunction)(onLoad)&&onLoad(this.viewModel.themeLayer,map);}},{key:"render",value:function render(){return null;}}]);return RangeThemeLayer;}(_react.default.Component),_class2.defaultProps={options:{}},_class2))||_class);exports["default"]=RangeThemeLayer; /***/ }), /***/ 5040: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var _interopRequireDefault=(__webpack_require__(4836)["default"]);Object.defineProperty(exports, "__esModule", ({value:true}));exports["default"]=void 0;var _classCallCheck2=_interopRequireDefault(__webpack_require__(5671));var _createClass2=_interopRequireDefault(__webpack_require__(3144));var _inherits2=_interopRequireDefault(__webpack_require__(9340));var _createSuper2=_interopRequireDefault(__webpack_require__(8557));var _mapboxGlEnhance=_interopRequireDefault(__webpack_require__(375));__webpack_require__(2395);var RangeThemeLayerViewModel=/*#__PURE__*/function(_mapboxgl$Evented){(0,_inherits2.default)(RangeThemeLayerViewModel,_mapboxgl$Evented);var _super=(0,_createSuper2.default)(RangeThemeLayerViewModel);function RangeThemeLayerViewModel(map,themeProps){var _this;(0,_classCallCheck2.default)(this,RangeThemeLayerViewModel);_this=_super.call(this);var layerName=themeProps.layerName,options=themeProps.options,layerId=themeProps.layerId,data=themeProps.data;_this.map=map;_this.layerName=layerName||layerId;options.id=options.id||layerId;_this.options=options;_this.data=data||[];_this._init();return _this;}(0,_createClass2.default)(RangeThemeLayerViewModel,[{key:"_init",value:function _init(){this.themeLayer=new _mapboxGlEnhance.default.supermap.RangeThemeLayer(this.layerName,this.options);this.map.addLayer(this.themeLayer);if(this.data&&this.data.length){this.setData(this.data);}}},{key:"setData",value:function setData(data){this.themeLayer.addFeatures(data);}}]);return RangeThemeLayerViewModel;}(_mapboxGlEnhance.default.Evented);exports["default"]=RangeThemeLayerViewModel; /***/ }), /***/ 3930: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var _interopRequireDefault=(__webpack_require__(4836)["default"]);Object.defineProperty(exports, "__esModule", ({value:true}));exports["default"]=void 0;var _classCallCheck2=_interopRequireDefault(__webpack_require__(5671));var _createClass2=_interopRequireDefault(__webpack_require__(3144));var _inherits2=_interopRequireDefault(__webpack_require__(9340));var _createSuper2=_interopRequireDefault(__webpack_require__(8557));var _compose2=_interopRequireDefault(__webpack_require__(8808));var _react=__webpack_require__(3899);var _mapGetter=_interopRequireDefault(__webpack_require__(9635));var _baseLayer=_interopRequireDefault(__webpack_require__(7006));var _util=__webpack_require__(9752);var _RanksymbolThemeLayerViewModel=_interopRequireDefault(__webpack_require__(8510));var _dec,_class;var RanksymbolThemeLayer=(_dec=(0,_compose2.default)(_mapGetter.default,_baseLayer.default),_dec(_class=/*#__PURE__*/function(_Component){(0,_inherits2.default)(RanksymbolThemeLayer,_Component);var _super=(0,_createSuper2.default)(RanksymbolThemeLayer);function RanksymbolThemeLayer(){(0,_classCallCheck2.default)(this,RanksymbolThemeLayer);return _super.apply(this,arguments);}(0,_createClass2.default)(RanksymbolThemeLayer,[{key:"loaded",value:function loaded(map){var onLoad=this.props.onLoad;this.viewModel=new _RanksymbolThemeLayerViewModel.default(map,this.props);(0,_util.isFunction)(onLoad)&&onLoad(this.viewModel.themeLayer,map);}},{key:"render",value:function render(){return null;}}]);return RanksymbolThemeLayer;}(_react.Component))||_class);exports["default"]=RanksymbolThemeLayer; /***/ }), /***/ 8510: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var _interopRequireDefault=(__webpack_require__(4836)["default"]);Object.defineProperty(exports, "__esModule", ({value:true}));exports["default"]=void 0;var _classCallCheck2=_interopRequireDefault(__webpack_require__(5671));var _createClass2=_interopRequireDefault(__webpack_require__(3144));var _inherits2=_interopRequireDefault(__webpack_require__(9340));var _createSuper2=_interopRequireDefault(__webpack_require__(8557));var _mapboxGlEnhance=_interopRequireDefault(__webpack_require__(375));__webpack_require__(2395);var RanksymbolThemeLayerViewModel=/*#__PURE__*/function(_mapboxgl$Evented){(0,_inherits2.default)(RanksymbolThemeLayerViewModel,_mapboxgl$Evented);var _super=(0,_createSuper2.default)(RanksymbolThemeLayerViewModel);function RanksymbolThemeLayerViewModel(map,themeProps){var _this;(0,_classCallCheck2.default)(this,RanksymbolThemeLayerViewModel);_this=_super.call(this);_this.map=map;var layerName=themeProps.layerName,options=themeProps.options,symbolType=themeProps.symbolType,layerId=themeProps.layerId,data=themeProps.data;_this.layerName=layerName||layerId;_this.symbolType=symbolType||'Circle';options.id=options.id||layerId;_this.options=options;_this.data=data||[];_this._init();return _this;}(0,_createClass2.default)(RanksymbolThemeLayerViewModel,[{key:"_init",value:function _init(){this.themeLayer=new _mapboxGlEnhance.default.supermap.RankSymbolThemeLayer(this.layerName,this.symbolType,this.options);this.map.addLayer(this.themeLayer);this.themeLayer.addFeatures(this.data);}}]);return RanksymbolThemeLayerViewModel;}(_mapboxGlEnhance.default.Evented);exports["default"]=RanksymbolThemeLayerViewModel; /***/ }), /***/ 1771: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var _interopRequireDefault=(__webpack_require__(4836)["default"]);Object.defineProperty(exports, "__esModule", ({value:true}));exports["default"]=void 0;var _classCallCheck2=_interopRequireDefault(__webpack_require__(5671));var _createClass2=_interopRequireDefault(__webpack_require__(3144));var _inherits2=_interopRequireDefault(__webpack_require__(9340));var _createSuper2=_interopRequireDefault(__webpack_require__(8557));var _compose2=_interopRequireDefault(__webpack_require__(8808));var _react=_interopRequireDefault(__webpack_require__(3899));var _mapGetter=_interopRequireDefault(__webpack_require__(9635));var _baseLayer=_interopRequireDefault(__webpack_require__(7006));var _RasterTileLayerViewModel=_interopRequireDefault(__webpack_require__(339));var _dec,_class,_class2;var RasterTileLayer=(_dec=(0,_compose2.default)(_mapGetter.default,_baseLayer.default),_dec(_class=(_class2=/*#__PURE__*/function(_React$Component){(0,_inherits2.default)(RasterTileLayer,_React$Component);var _super=(0,_createSuper2.default)(RasterTileLayer);function RasterTileLayer(){(0,_classCallCheck2.default)(this,RasterTileLayer);return _super.apply(this,arguments);}(0,_createClass2.default)(RasterTileLayer,[{key:"loaded",value:function loaded(map){this.viewModel=new _RasterTileLayerViewModel.default(map,this.props);}},{key:"removed",value:function removed(){this.viewModel=null;}},{key:"render",value:function render(){return null;}}]);return RasterTileLayer;}(_react.default.Component),_class2.defaultProps={scheme:'xyz',visible:true,opacity:1},_class2))||_class);exports["default"]=RasterTileLayer; /***/ }), /***/ 339: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var _interopRequireDefault=(__webpack_require__(4836)["default"]);Object.defineProperty(exports, "__esModule", ({value:true}));exports["default"]=void 0;var _classCallCheck2=_interopRequireDefault(__webpack_require__(5671));var _createClass2=_interopRequireDefault(__webpack_require__(3144));var _inherits2=_interopRequireDefault(__webpack_require__(9340));var _createSuper2=_interopRequireDefault(__webpack_require__(8557));var _mapboxGlEnhance=_interopRequireDefault(__webpack_require__(375));__webpack_require__(2395);var RasterTileLayerViewModel=/*#__PURE__*/function(_mapboxgl$Evented){(0,_inherits2.default)(RasterTileLayerViewModel,_mapboxgl$Evented);var _super=(0,_createSuper2.default)(RasterTileLayerViewModel);function RasterTileLayerViewModel(map,rasterLayerOptions){var _this;(0,_classCallCheck2.default)(this,RasterTileLayerViewModel);_this=_super.call(this);_this.map=map;var layerId=rasterLayerOptions.layerId,tileSize=rasterLayerOptions.tileSize,mapUrl=rasterLayerOptions.mapUrl,tiles=rasterLayerOptions.tiles,bounds=rasterLayerOptions.bounds,_rasterLayerOptions$m=rasterLayerOptions.minZoom,minZoom=_rasterLayerOptions$m===void 0?0:_rasterLayerOptions$m,_rasterLayerOptions$m2=rasterLayerOptions.maxZoom,maxZoom=_rasterLayerOptions$m2===void 0?22:_rasterLayerOptions$m2,attribution=rasterLayerOptions.attribution,_rasterLayerOptions$s=rasterLayerOptions.scheme,scheme=_rasterLayerOptions$s===void 0?'xyz':_rasterLayerOptions$s,_rasterLayerOptions$v=rasterLayerOptions.visible,visible=_rasterLayerOptions$v===void 0?true:_rasterLayerOptions$v,_rasterLayerOptions$o=rasterLayerOptions.opacity,opacity=_rasterLayerOptions$o===void 0?1:_rasterLayerOptions$o,before=rasterLayerOptions.before;_this.layerId=layerId;_this.tileSize=tileSize;_this.mapUrl=mapUrl;_this.tiles=tiles;_this.bounds=bounds;_this.minZoom=minZoom;_this.maxZoom=maxZoom;_this.attribution=attribution;_this.scheme=scheme;_this.opacity=opacity;_this.visibility=visible?'visible':'none';_this.before=before;// enhance扩展,传iserver标识是iserver rest map _this.rasterSource='';_this._init();return _this;}(0,_createClass2.default)(RasterTileLayerViewModel,[{key:"_init",value:function _init(){if(this.mapUrl){this._addRestMapLayer();}else{this._addLayer();}}},{key:"_addRestMapLayer",value:function _addRestMapLayer(){var _this2=this;var service=new _mapboxGlEnhance.default.supermap.MapService(this.mapUrl);service.getMapInfo(function(mapObj){if(!_this2.layerId){_this2.layerId=mapObj.name;}if(!_this2.tileSize&&mapObj.viewer){_this2.tileSize=mapObj.viewer.width;}var bounds=mapObj.bounds;if(!_this2.bounds&&bounds){_this2.bounds=[bounds.left,bounds.bottom,bounds.right,bounds.top];}_this2.rasterSource='iserver';_this2.tiles=[_this2.mapUrl];_this2._addLayer(mapObj);});}},{key:"_addLayer",value:function _addLayer(){this.map.addLayer({id:this.layerId||"raster-layer-".concat(new Date().getTime()),type:'raster',layout:{visibility:this.visibility},paint:{'raster-opacity':this.opacity},source:{bounds:this.bounds||[-180,-85.051129,180,85.051129],type:'raster',tileSize:this.tileSize||256,tiles:this.tiles,rasterSource:this.rasterSource,minzoom:this.minZoom,maxzoom:this.maxZoom,scheme:this.scheme}},this.before);}}]);return RasterTileLayerViewModel;}(_mapboxGlEnhance.default.Evented);exports["default"]=RasterTileLayerViewModel; /***/ }), /***/ 4204: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var _interopRequireDefault=(__webpack_require__(4836)["default"]);Object.defineProperty(exports, "__esModule", ({value:true}));exports["default"]=void 0;var _classCallCheck2=_interopRequireDefault(__webpack_require__(5671));var _createClass2=_interopRequireDefault(__webpack_require__(3144));var _inherits2=_interopRequireDefault(__webpack_require__(9340));var _createSuper2=_interopRequireDefault(__webpack_require__(8557));var _compose2=_interopRequireDefault(__webpack_require__(8808));var _react=_interopRequireDefault(__webpack_require__(3899));var _lodash=_interopRequireDefault(__webpack_require__(2307));var _mapGetter=_interopRequireDefault(__webpack_require__(9635));var _baseLayer=_interopRequireDefault(__webpack_require__(7006));var _util=__webpack_require__(9752);var _UniqueThemeLayerViewModel=_interopRequireDefault(__webpack_require__(2658));var _dec,_class,_class2;var UniqueThemeLayer=(_dec=(0,_compose2.default)(_mapGetter.default,_baseLayer.default),_dec(_class=(_class2=/*#__PURE__*/function(_React$Component){(0,_inherits2.default)(UniqueThemeLayer,_React$Component);var _super=(0,_createSuper2.default)(UniqueThemeLayer);function UniqueThemeLayer(){(0,_classCallCheck2.default)(this,UniqueThemeLayer);return _super.apply(this,arguments);}(0,_createClass2.default)(UniqueThemeLayer,[{key:"componentDidUpdate",value:function componentDidUpdate(prevProps){var data=this.props.data;if(!(0,_lodash.default)(prevProps.data,data)&&this.viewModel){this.viewModel.setData(data);}}},{key:"loaded",value:function loaded(map){var onLoad=this.props.onLoad;this.viewModel=new _UniqueThemeLayerViewModel.default(map,this.props);(0,_util.isFunction)(onLoad)&&onLoad(this.viewModel.themeLayer,map);}},{key:"render",value:function render(){return null;}}]);return UniqueThemeLayer;}(_react.default.Component),_class2.defaultProps={options:{}},_class2))||_class);exports["default"]=UniqueThemeLayer; /***/ }), /***/ 2658: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var _interopRequireDefault=(__webpack_require__(4836)["default"]);Object.defineProperty(exports, "__esModule", ({value:true}));exports["default"]=void 0;var _classCallCheck2=_interopRequireDefault(__webpack_require__(5671));var _createClass2=_interopRequireDefault(__webpack_require__(3144));var _inherits2=_interopRequireDefault(__webpack_require__(9340));var _createSuper2=_interopRequireDefault(__webpack_require__(8557));var _mapboxGlEnhance=_interopRequireDefault(__webpack_require__(375));__webpack_require__(2395);var UniqueThemeLayerViewModel=/*#__PURE__*/function(_mapboxgl$Evented){(0,_inherits2.default)(UniqueThemeLayerViewModel,_mapboxgl$Evented);var _super=(0,_createSuper2.default)(UniqueThemeLayerViewModel);function UniqueThemeLayerViewModel(map,themeProps){var _this;(0,_classCallCheck2.default)(this,UniqueThemeLayerViewModel);_this=_super.call(this);_this.map=map;var options=themeProps.options,layerId=themeProps.layerId,data=themeProps.data,layerName=themeProps.layerName;_this.layerName=layerName||layerId;options.id=options.id||layerId;_this.options=options;_this.data=data||[];_this._init();return _this;}(0,_createClass2.default)(UniqueThemeLayerViewModel,[{key:"_init",value:function _init(){this.themeLayer=new _mapboxGlEnhance.default.supermap.UniqueThemeLayer(this.layerName,this.options);this.map.addLayer(this.themeLayer);if(this.data&&this.data.length){this.setData(this.data);}}},{key:"setData",value:function setData(data){this.themeLayer.addFeatures(data);}}]);return UniqueThemeLayerViewModel;}(_mapboxGlEnhance.default.Evented);exports["default"]=UniqueThemeLayerViewModel; /***/ }), /***/ 2125: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var _interopRequireDefault=(__webpack_require__(4836)["default"]);Object.defineProperty(exports, "__esModule", ({value:true}));exports["default"]=void 0;var _classCallCheck2=_interopRequireDefault(__webpack_require__(5671));var _createClass2=_interopRequireDefault(__webpack_require__(3144));var _inherits2=_interopRequireDefault(__webpack_require__(9340));var _createSuper2=_interopRequireDefault(__webpack_require__(8557));var _compose2=_interopRequireDefault(__webpack_require__(8808));var _react=_interopRequireDefault(__webpack_require__(3899));var _mapGetter=_interopRequireDefault(__webpack_require__(9635));var _baseLayer=_interopRequireDefault(__webpack_require__(7006));var _dec,_class;var VectorTileLayer=(_dec=(0,_compose2.default)(_mapGetter.default,_baseLayer.default),_dec(_class=/*#__PURE__*/function(_React$Component){(0,_inherits2.default)(VectorTileLayer,_React$Component);var _super=(0,_createSuper2.default)(VectorTileLayer);function VectorTileLayer(){(0,_classCallCheck2.default)(this,VectorTileLayer);return _super.apply(this,arguments);}(0,_createClass2.default)(VectorTileLayer,[{key:"loaded",value:function loaded(map){if(map&&map['addStyle']){map['addStyle'](this.props.styleOptions,this.props.before);}}},{key:"render",value:function render(){return null;}}]);return VectorTileLayer;}(_react.default.Component))||_class);exports["default"]=VectorTileLayer; /***/ }), /***/ 8874: /***/ (function(module) { "use strict"; module.exports = { "aliceblue": [240, 248, 255], "antiquewhite": [250, 235, 215], "aqua": [0, 255, 255], "aquamarine": [127, 255, 212], "azure": [240, 255, 255], "beige": [245, 245, 220], "bisque": [255, 228, 196], "black": [0, 0, 0], "blanchedalmond": [255, 235, 205], "blue": [0, 0, 255], "blueviolet": [138, 43, 226], "brown": [165, 42, 42], "burlywood": [222, 184, 135], "cadetblue": [95, 158, 160], "chartreuse": [127, 255, 0], "chocolate": [210, 105, 30], "coral": [255, 127, 80], "cornflowerblue": [100, 149, 237], "cornsilk": [255, 248, 220], "crimson": [220, 20, 60], "cyan": [0, 255, 255], "darkblue": [0, 0, 139], "darkcyan": [0, 139, 139], "darkgoldenrod": [184, 134, 11], "darkgray": [169, 169, 169], "darkgreen": [0, 100, 0], "darkgrey": [169, 169, 169], "darkkhaki": [189, 183, 107], "darkmagenta": [139, 0, 139], "darkolivegreen": [85, 107, 47], "darkorange": [255, 140, 0], "darkorchid": [153, 50, 204], "darkred": [139, 0, 0], "darksalmon": [233, 150, 122], "darkseagreen": [143, 188, 143], "darkslateblue": [72, 61, 139], "darkslategray": [47, 79, 79], "darkslategrey": [47, 79, 79], "darkturquoise": [0, 206, 209], "darkviolet": [148, 0, 211], "deeppink": [255, 20, 147], "deepskyblue": [0, 191, 255], "dimgray": [105, 105, 105], "dimgrey": [105, 105, 105], "dodgerblue": [30, 144, 255], "firebrick": [178, 34, 34], "floralwhite": [255, 250, 240], "forestgreen": [34, 139, 34], "fuchsia": [255, 0, 255], "gainsboro": [220, 220, 220], "ghostwhite": [248, 248, 255], "gold": [255, 215, 0], "goldenrod": [218, 165, 32], "gray": [128, 128, 128], "green": [0, 128, 0], "greenyellow": [173, 255, 47], "grey": [128, 128, 128], "honeydew": [240, 255, 240], "hotpink": [255, 105, 180], "indianred": [205, 92, 92], "indigo": [75, 0, 130], "ivory": [255, 255, 240], "khaki": [240, 230, 140], "lavender": [230, 230, 250], "lavenderblush": [255, 240, 245], "lawngreen": [124, 252, 0], "lemonchiffon": [255, 250, 205], "lightblue": [173, 216, 230], "lightcoral": [240, 128, 128], "lightcyan": [224, 255, 255], "lightgoldenrodyellow": [250, 250, 210], "lightgray": [211, 211, 211], "lightgreen": [144, 238, 144], "lightgrey": [211, 211, 211], "lightpink": [255, 182, 193], "lightsalmon": [255, 160, 122], "lightseagreen": [32, 178, 170], "lightskyblue": [135, 206, 250], "lightslategray": [119, 136, 153], "lightslategrey": [119, 136, 153], "lightsteelblue": [176, 196, 222], "lightyellow": [255, 255, 224], "lime": [0, 255, 0], "limegreen": [50, 205, 50], "linen": [250, 240, 230], "magenta": [255, 0, 255], "maroon": [128, 0, 0], "mediumaquamarine": [102, 205, 170], "mediumblue": [0, 0, 205], "mediumorchid": [186, 85, 211], "mediumpurple": [147, 112, 219], "mediumseagreen": [60, 179, 113], "mediumslateblue": [123, 104, 238], "mediumspringgreen": [0, 250, 154], "mediumturquoise": [72, 209, 204], "mediumvioletred": [199, 21, 133], "midnightblue": [25, 25, 112], "mintcream": [245, 255, 250], "mistyrose": [255, 228, 225], "moccasin": [255, 228, 181], "navajowhite": [255, 222, 173], "navy": [0, 0, 128], "oldlace": [253, 245, 230], "olive": [128, 128, 0], "olivedrab": [107, 142, 35], "orange": [255, 165, 0], "orangered": [255, 69, 0], "orchid": [218, 112, 214], "palegoldenrod": [238, 232, 170], "palegreen": [152, 251, 152], "paleturquoise": [175, 238, 238], "palevioletred": [219, 112, 147], "papayawhip": [255, 239, 213], "peachpuff": [255, 218, 185], "peru": [205, 133, 63], "pink": [255, 192, 203], "plum": [221, 160, 221], "powderblue": [176, 224, 230], "purple": [128, 0, 128], "rebeccapurple": [102, 51, 153], "red": [255, 0, 0], "rosybrown": [188, 143, 143], "royalblue": [65, 105, 225], "saddlebrown": [139, 69, 19], "salmon": [250, 128, 114], "sandybrown": [244, 164, 96], "seagreen": [46, 139, 87], "seashell": [255, 245, 238], "sienna": [160, 82, 45], "silver": [192, 192, 192], "skyblue": [135, 206, 235], "slateblue": [106, 90, 205], "slategray": [112, 128, 144], "slategrey": [112, 128, 144], "snow": [255, 250, 250], "springgreen": [0, 255, 127], "steelblue": [70, 130, 180], "tan": [210, 180, 140], "teal": [0, 128, 128], "thistle": [216, 191, 216], "tomato": [255, 99, 71], "turquoise": [64, 224, 208], "violet": [238, 130, 238], "wheat": [245, 222, 179], "white": [255, 255, 255], "whitesmoke": [245, 245, 245], "yellow": [255, 255, 0], "yellowgreen": [154, 205, 50] }; /***/ }), /***/ 7187: /***/ (function(module) { "use strict"; // Copyright Joyent, Inc. and other Node contributors. // // 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. var R = typeof Reflect === 'object' ? Reflect : null var ReflectApply = R && typeof R.apply === 'function' ? R.apply : function ReflectApply(target, receiver, args) { return Function.prototype.apply.call(target, receiver, args); } var ReflectOwnKeys if (R && typeof R.ownKeys === 'function') { ReflectOwnKeys = R.ownKeys } else if (Object.getOwnPropertySymbols) { ReflectOwnKeys = function ReflectOwnKeys(target) { return Object.getOwnPropertyNames(target) .concat(Object.getOwnPropertySymbols(target)); }; } else { ReflectOwnKeys = function ReflectOwnKeys(target) { return Object.getOwnPropertyNames(target); }; } function ProcessEmitWarning(warning) { if (console && console.warn) console.warn(warning); } var NumberIsNaN = Number.isNaN || function NumberIsNaN(value) { return value !== value; } function EventEmitter() { EventEmitter.init.call(this); } module.exports = EventEmitter; module.exports.once = once; // Backwards-compat with node 0.10.x EventEmitter.EventEmitter = EventEmitter; EventEmitter.prototype._events = undefined; EventEmitter.prototype._eventsCount = 0; EventEmitter.prototype._maxListeners = undefined; // By default EventEmitters will print a warning if more than 10 listeners are // added to it. This is a useful default which helps finding memory leaks. var defaultMaxListeners = 10; function checkListener(listener) { if (typeof listener !== 'function') { throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener); } } Object.defineProperty(EventEmitter, 'defaultMaxListeners', { enumerable: true, get: function() { return defaultMaxListeners; }, set: function(arg) { if (typeof arg !== 'number' || arg < 0 || NumberIsNaN(arg)) { throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + arg + '.'); } defaultMaxListeners = arg; } }); EventEmitter.init = function() { if (this._events === undefined || this._events === Object.getPrototypeOf(this)._events) { this._events = Object.create(null); this._eventsCount = 0; } this._maxListeners = this._maxListeners || undefined; }; // Obviously not all Emitters should be limited to 10. This function allows // that to be increased. Set to zero for unlimited. EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) { if (typeof n !== 'number' || n < 0 || NumberIsNaN(n)) { throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n + '.'); } this._maxListeners = n; return this; }; function _getMaxListeners(that) { if (that._maxListeners === undefined) return EventEmitter.defaultMaxListeners; return that._maxListeners; } EventEmitter.prototype.getMaxListeners = function getMaxListeners() { return _getMaxListeners(this); }; EventEmitter.prototype.emit = function emit(type) { var args = []; for (var i = 1; i < arguments.length; i++) args.push(arguments[i]); var doError = (type === 'error'); var events = this._events; if (events !== undefined) doError = (doError && events.error === undefined); else if (!doError) return false; // If there is no 'error' event listener then throw. if (doError) { var er; if (args.length > 0) er = args[0]; if (er instanceof Error) { // Note: The comments on the `throw` lines are intentional, they show // up in Node's output if this results in an unhandled exception. throw er; // Unhandled 'error' event } // At least give some kind of context to the user var err = new Error('Unhandled error.' + (er ? ' (' + er.message + ')' : '')); err.context = er; throw err; // Unhandled 'error' event } var handler = events[type]; if (handler === undefined) return false; if (typeof handler === 'function') { ReflectApply(handler, this, args); } else { var len = handler.length; var listeners = arrayClone(handler, len); for (var i = 0; i < len; ++i) ReflectApply(listeners[i], this, args); } return true; }; function _addListener(target, type, listener, prepend) { var m; var events; var existing; checkListener(listener); events = target._events; if (events === undefined) { events = target._events = Object.create(null); target._eventsCount = 0; } else { // To avoid recursion in the case that type === "newListener"! Before // adding it to the listeners, first emit "newListener". if (events.newListener !== undefined) { target.emit('newListener', type, listener.listener ? listener.listener : listener); // Re-assign `events` because a newListener handler could have caused the // this._events to be assigned to a new object events = target._events; } existing = events[type]; } if (existing === undefined) { // Optimize the case of one listener. Don't need the extra array object. existing = events[type] = listener; ++target._eventsCount; } else { if (typeof existing === 'function') { // Adding the second element, need to change to array. existing = events[type] = prepend ? [listener, existing] : [existing, listener]; // If we've already got an array, just append. } else if (prepend) { existing.unshift(listener); } else { existing.push(listener); } // Check for listener leak m = _getMaxListeners(target); if (m > 0 && existing.length > m && !existing.warned) { existing.warned = true; // No error code for this since it is a Warning // eslint-disable-next-line no-restricted-syntax var w = new Error('Possible EventEmitter memory leak detected. ' + existing.length + ' ' + String(type) + ' listeners ' + 'added. Use emitter.setMaxListeners() to ' + 'increase limit'); w.name = 'MaxListenersExceededWarning'; w.emitter = target; w.type = type; w.count = existing.length; ProcessEmitWarning(w); } } return target; } EventEmitter.prototype.addListener = function addListener(type, listener) { return _addListener(this, type, listener, false); }; EventEmitter.prototype.on = EventEmitter.prototype.addListener; EventEmitter.prototype.prependListener = function prependListener(type, listener) { return _addListener(this, type, listener, true); }; function onceWrapper() { if (!this.fired) { this.target.removeListener(this.type, this.wrapFn); this.fired = true; if (arguments.length === 0) return this.listener.call(this.target); return this.listener.apply(this.target, arguments); } } function _onceWrap(target, type, listener) { var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener }; var wrapped = onceWrapper.bind(state); wrapped.listener = listener; state.wrapFn = wrapped; return wrapped; } EventEmitter.prototype.once = function once(type, listener) { checkListener(listener); this.on(type, _onceWrap(this, type, listener)); return this; }; EventEmitter.prototype.prependOnceListener = function prependOnceListener(type, listener) { checkListener(listener); this.prependListener(type, _onceWrap(this, type, listener)); return this; }; // Emits a 'removeListener' event if and only if the listener was removed. EventEmitter.prototype.removeListener = function removeListener(type, listener) { var list, events, position, i, originalListener; checkListener(listener); events = this._events; if (events === undefined) return this; list = events[type]; if (list === undefined) return this; if (list === listener || list.listener === listener) { if (--this._eventsCount === 0) this._events = Object.create(null); else { delete events[type]; if (events.removeListener) this.emit('removeListener', type, list.listener || listener); } } else if (typeof list !== 'function') { position = -1; for (i = list.length - 1; i >= 0; i--) { if (list[i] === listener || list[i].listener === listener) { originalListener = list[i].listener; position = i; break; } } if (position < 0) return this; if (position === 0) list.shift(); else { spliceOne(list, position); } if (list.length === 1) events[type] = list[0]; if (events.removeListener !== undefined) this.emit('removeListener', type, originalListener || listener); } return this; }; EventEmitter.prototype.off = EventEmitter.prototype.removeListener; EventEmitter.prototype.removeAllListeners = function removeAllListeners(type) { var listeners, events, i; events = this._events; if (events === undefined) return this; // not listening for removeListener, no need to emit if (events.removeListener === undefined) { if (arguments.length === 0) { this._events = Object.create(null); this._eventsCount = 0; } else if (events[type] !== undefined) { if (--this._eventsCount === 0) this._events = Object.create(null); else delete events[type]; } return this; } // emit removeListener for all listeners on all events if (arguments.length === 0) { var keys = Object.keys(events); var key; for (i = 0; i < keys.length; ++i) { key = keys[i]; if (key === 'removeListener') continue; this.removeAllListeners(key); } this.removeAllListeners('removeListener'); this._events = Object.create(null); this._eventsCount = 0; return this; } listeners = events[type]; if (typeof listeners === 'function') { this.removeListener(type, listeners); } else if (listeners !== undefined) { // LIFO order for (i = listeners.length - 1; i >= 0; i--) { this.removeListener(type, listeners[i]); } } return this; }; function _listeners(target, type, unwrap) { var events = target._events; if (events === undefined) return []; var evlistener = events[type]; if (evlistener === undefined) return []; if (typeof evlistener === 'function') return unwrap ? [evlistener.listener || evlistener] : [evlistener]; return unwrap ? unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length); } EventEmitter.prototype.listeners = function listeners(type) { return _listeners(this, type, true); }; EventEmitter.prototype.rawListeners = function rawListeners(type) { return _listeners(this, type, false); }; EventEmitter.listenerCount = function(emitter, type) { if (typeof emitter.listenerCount === 'function') { return emitter.listenerCount(type); } else { return listenerCount.call(emitter, type); } }; EventEmitter.prototype.listenerCount = listenerCount; function listenerCount(type) { var events = this._events; if (events !== undefined) { var evlistener = events[type]; if (typeof evlistener === 'function') { return 1; } else if (evlistener !== undefined) { return evlistener.length; } } return 0; } EventEmitter.prototype.eventNames = function eventNames() { return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : []; }; function arrayClone(arr, n) { var copy = new Array(n); for (var i = 0; i < n; ++i) copy[i] = arr[i]; return copy; } function spliceOne(list, index) { for (; index + 1 < list.length; index++) list[index] = list[index + 1]; list.pop(); } function unwrapListeners(arr) { var ret = new Array(arr.length); for (var i = 0; i < ret.length; ++i) { ret[i] = arr[i].listener || arr[i]; } return ret; } function once(emitter, name) { return new Promise(function (resolve, reject) { function errorListener(err) { emitter.removeListener(name, resolver); reject(err); } function resolver() { if (typeof emitter.removeListener === 'function') { emitter.removeListener('error', errorListener); } resolve([].slice.call(arguments)); }; eventTargetAgnosticAddListener(emitter, name, resolver, { once: true }); if (name !== 'error') { addErrorHandlerIfEventEmitter(emitter, errorListener, { once: true }); } }); } function addErrorHandlerIfEventEmitter(emitter, handler, flags) { if (typeof emitter.on === 'function') { eventTargetAgnosticAddListener(emitter, 'error', handler, flags); } } function eventTargetAgnosticAddListener(emitter, name, listener, flags) { if (typeof emitter.on === 'function') { if (flags.once) { emitter.once(name, listener); } else { emitter.on(name, listener); } } else if (typeof emitter.addEventListener === 'function') { // EventTarget does not have `error` event semantics like Node // EventEmitters, we do not listen for `error` events here. emitter.addEventListener(name, function wrapListener(arg) { // IE does not have builtin `{ once: true }` support so we // have to do it manually. if (flags.once) { emitter.removeEventListener(name, wrapListener); } listener(arg); }); } else { throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type ' + typeof emitter); } } /***/ }), /***/ 8679: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; var reactIs = __webpack_require__(7109); /** * Copyright 2015, Yahoo! Inc. * Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms. */ var REACT_STATICS = { childContextTypes: true, contextType: true, contextTypes: true, defaultProps: true, displayName: true, getDefaultProps: true, getDerivedStateFromError: true, getDerivedStateFromProps: true, mixins: true, propTypes: true, type: true }; var KNOWN_STATICS = { name: true, length: true, prototype: true, caller: true, callee: true, arguments: true, arity: true }; var FORWARD_REF_STATICS = { '$$typeof': true, render: true, defaultProps: true, displayName: true, propTypes: true }; var MEMO_STATICS = { '$$typeof': true, compare: true, defaultProps: true, displayName: true, propTypes: true, type: true }; var TYPE_STATICS = {}; TYPE_STATICS[reactIs.ForwardRef] = FORWARD_REF_STATICS; TYPE_STATICS[reactIs.Memo] = MEMO_STATICS; function getStatics(component) { // React v16.11 and below if (reactIs.isMemo(component)) { return MEMO_STATICS; } // React v16.12 and above return TYPE_STATICS[component['$$typeof']] || REACT_STATICS; } var defineProperty = Object.defineProperty; var getOwnPropertyNames = Object.getOwnPropertyNames; var getOwnPropertySymbols = Object.getOwnPropertySymbols; var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; var getPrototypeOf = Object.getPrototypeOf; var objectPrototype = Object.prototype; function hoistNonReactStatics(targetComponent, sourceComponent, blacklist) { if (typeof sourceComponent !== 'string') { // don't hoist over string (html) components if (objectPrototype) { var inheritedComponent = getPrototypeOf(sourceComponent); if (inheritedComponent && inheritedComponent !== objectPrototype) { hoistNonReactStatics(targetComponent, inheritedComponent, blacklist); } } var keys = getOwnPropertyNames(sourceComponent); if (getOwnPropertySymbols) { keys = keys.concat(getOwnPropertySymbols(sourceComponent)); } var targetStatics = getStatics(targetComponent); var sourceStatics = getStatics(sourceComponent); for (var i = 0; i < keys.length; ++i) { var key = keys[i]; if (!KNOWN_STATICS[key] && !(blacklist && blacklist[key]) && !(sourceStatics && sourceStatics[key]) && !(targetStatics && targetStatics[key])) { var descriptor = getOwnPropertyDescriptor(sourceComponent, key); try { // Avoid failures from read-only properties defineProperty(targetComponent, key, descriptor); } catch (e) {} } } } return targetComponent; } module.exports = hoistNonReactStatics; /***/ }), /***/ 6103: /***/ (function(__unused_webpack_module, exports) { "use strict"; /** @license React v16.13.1 * react-is.production.min.js * * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var b="function"===typeof Symbol&&Symbol.for,c=b?Symbol.for("react.element"):60103,d=b?Symbol.for("react.portal"):60106,e=b?Symbol.for("react.fragment"):60107,f=b?Symbol.for("react.strict_mode"):60108,g=b?Symbol.for("react.profiler"):60114,h=b?Symbol.for("react.provider"):60109,k=b?Symbol.for("react.context"):60110,l=b?Symbol.for("react.async_mode"):60111,m=b?Symbol.for("react.concurrent_mode"):60111,n=b?Symbol.for("react.forward_ref"):60112,p=b?Symbol.for("react.suspense"):60113,q=b? Symbol.for("react.suspense_list"):60120,r=b?Symbol.for("react.memo"):60115,t=b?Symbol.for("react.lazy"):60116,v=b?Symbol.for("react.block"):60121,w=b?Symbol.for("react.fundamental"):60117,x=b?Symbol.for("react.responder"):60118,y=b?Symbol.for("react.scope"):60119; function z(a){if("object"===typeof a&&null!==a){var u=a.$$typeof;switch(u){case c:switch(a=a.type,a){case l:case m:case e:case g:case f:case p:return a;default:switch(a=a&&a.$$typeof,a){case k:case n:case t:case r:case h:return a;default:return u}}case d:return u}}}function A(a){return z(a)===m}exports.AsyncMode=l;exports.ConcurrentMode=m;exports.ContextConsumer=k;exports.ContextProvider=h;exports.Element=c;exports.ForwardRef=n;exports.Fragment=e;exports.Lazy=t;exports.Memo=r;exports.Portal=d; exports.Profiler=g;exports.StrictMode=f;exports.Suspense=p;exports.isAsyncMode=function(a){return A(a)||z(a)===l};exports.isConcurrentMode=A;exports.isContextConsumer=function(a){return z(a)===k};exports.isContextProvider=function(a){return z(a)===h};exports.isElement=function(a){return"object"===typeof a&&null!==a&&a.$$typeof===c};exports.isForwardRef=function(a){return z(a)===n};exports.isFragment=function(a){return z(a)===e};exports.isLazy=function(a){return z(a)===t}; exports.isMemo=function(a){return z(a)===r};exports.isPortal=function(a){return z(a)===d};exports.isProfiler=function(a){return z(a)===g};exports.isStrictMode=function(a){return z(a)===f};exports.isSuspense=function(a){return z(a)===p}; exports.isValidElementType=function(a){return"string"===typeof a||"function"===typeof a||a===e||a===m||a===g||a===f||a===p||a===q||"object"===typeof a&&null!==a&&(a.$$typeof===t||a.$$typeof===r||a.$$typeof===h||a.$$typeof===k||a.$$typeof===n||a.$$typeof===w||a.$$typeof===x||a.$$typeof===y||a.$$typeof===v)};exports.typeOf=z; /***/ }), /***/ 7109: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; if (true) { module.exports = __webpack_require__(6103); } else {} /***/ }), /***/ 5717: /***/ (function(module) { if (typeof Object.create === 'function') { // implementation from standard node.js 'util' module module.exports = function inherits(ctor, superCtor) { if (superCtor) { ctor.super_ = superCtor ctor.prototype = Object.create(superCtor.prototype, { constructor: { value: ctor, enumerable: false, writable: true, configurable: true } }) } }; } else { // old school shim for old browsers module.exports = function inherits(ctor, superCtor) { if (superCtor) { ctor.super_ = superCtor var TempCtor = function () {} TempCtor.prototype = superCtor.prototype ctor.prototype = new TempCtor() ctor.prototype.constructor = ctor } } } /***/ }), /***/ 1633: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { /** * lodash (Custom Build) * Build: `lodash modularize exports="npm" -o ./` * Copyright jQuery Foundation and other contributors * Released under MIT license * Based on Underscore.js 1.8.3 * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors */ /** Used as references for various `Number` constants. */ var INFINITY = 1 / 0; /** `Object#toString` result references. */ var symbolTag = '[object Symbol]'; /** Used to compose unicode character classes. */ var rsAstralRange = '\\ud800-\\udfff', rsComboMarksRange = '\\u0300-\\u036f\\ufe20-\\ufe23', rsComboSymbolsRange = '\\u20d0-\\u20f0', rsVarRange = '\\ufe0e\\ufe0f'; /** Used to compose unicode capture groups. */ var rsAstral = '[' + rsAstralRange + ']', rsCombo = '[' + rsComboMarksRange + rsComboSymbolsRange + ']', rsFitz = '\\ud83c[\\udffb-\\udfff]', rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')', rsNonAstral = '[^' + rsAstralRange + ']', rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}', rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]', rsZWJ = '\\u200d'; /** Used to compose unicode regexes. */ var reOptMod = rsModifier + '?', rsOptVar = '[' + rsVarRange + ']?', rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*', rsSeq = rsOptVar + reOptMod + rsOptJoin, rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')'; /** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */ var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g'); /** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */ var reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboMarksRange + rsComboSymbolsRange + rsVarRange + ']'); /** Detect free variable `global` from Node.js. */ var freeGlobal = typeof __webpack_require__.g == 'object' && __webpack_require__.g && __webpack_require__.g.Object === Object && __webpack_require__.g; /** Detect free variable `self`. */ var freeSelf = typeof self == 'object' && self && self.Object === Object && self; /** Used as a reference to the global object. */ var root = freeGlobal || freeSelf || Function('return this')(); /** * Converts an ASCII `string` to an array. * * @private * @param {string} string The string to convert. * @returns {Array} Returns the converted array. */ function asciiToArray(string) { return string.split(''); } /** * Checks if `string` contains Unicode symbols. * * @private * @param {string} string The string to inspect. * @returns {boolean} Returns `true` if a symbol is found, else `false`. */ function hasUnicode(string) { return reHasUnicode.test(string); } /** * Converts `string` to an array. * * @private * @param {string} string The string to convert. * @returns {Array} Returns the converted array. */ function stringToArray(string) { return hasUnicode(string) ? unicodeToArray(string) : asciiToArray(string); } /** * Converts a Unicode `string` to an array. * * @private * @param {string} string The string to convert. * @returns {Array} Returns the converted array. */ function unicodeToArray(string) { return string.match(reUnicode) || []; } /** Used for built-in method references. */ var objectProto = Object.prototype; /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) * of values. */ var objectToString = objectProto.toString; /** Built-in value references. */ var Symbol = root.Symbol; /** Used to convert symbols to primitives and strings. */ var symbolProto = Symbol ? Symbol.prototype : undefined, symbolToString = symbolProto ? symbolProto.toString : undefined; /** * The base implementation of `_.slice` without an iteratee call guard. * * @private * @param {Array} array The array to slice. * @param {number} [start=0] The start position. * @param {number} [end=array.length] The end position. * @returns {Array} Returns the slice of `array`. */ function baseSlice(array, start, end) { var index = -1, length = array.length; if (start < 0) { start = -start > length ? 0 : (length + start); } end = end > length ? length : end; if (end < 0) { end += length; } length = start > end ? 0 : ((end - start) >>> 0); start >>>= 0; var result = Array(length); while (++index < length) { result[index] = array[index + start]; } return result; } /** * The base implementation of `_.toString` which doesn't convert nullish * values to empty strings. * * @private * @param {*} value The value to process. * @returns {string} Returns the string. */ function baseToString(value) { // Exit early for strings to avoid a performance hit in some environments. if (typeof value == 'string') { return value; } if (isSymbol(value)) { return symbolToString ? symbolToString.call(value) : ''; } var result = (value + ''); return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; } /** * Casts `array` to a slice if it's needed. * * @private * @param {Array} array The array to inspect. * @param {number} start The start position. * @param {number} [end=array.length] The end position. * @returns {Array} Returns the cast slice. */ function castSlice(array, start, end) { var length = array.length; end = end === undefined ? length : end; return (!start && end >= length) ? array : baseSlice(array, start, end); } /** * Creates a function like `_.lowerFirst`. * * @private * @param {string} methodName The name of the `String` case method to use. * @returns {Function} Returns the new case function. */ function createCaseFirst(methodName) { return function(string) { string = toString(string); var strSymbols = hasUnicode(string) ? stringToArray(string) : undefined; var chr = strSymbols ? strSymbols[0] : string.charAt(0); var trailing = strSymbols ? castSlice(strSymbols, 1).join('') : string.slice(1); return chr[methodName]() + trailing; }; } /** * Checks if `value` is object-like. A value is object-like if it's not `null` * and has a `typeof` result of "object". * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is object-like, else `false`. * @example * * _.isObjectLike({}); * // => true * * _.isObjectLike([1, 2, 3]); * // => true * * _.isObjectLike(_.noop); * // => false * * _.isObjectLike(null); * // => false */ function isObjectLike(value) { return !!value && typeof value == 'object'; } /** * Checks if `value` is classified as a `Symbol` primitive or object. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. * @example * * _.isSymbol(Symbol.iterator); * // => true * * _.isSymbol('abc'); * // => false */ function isSymbol(value) { return typeof value == 'symbol' || (isObjectLike(value) && objectToString.call(value) == symbolTag); } /** * Converts `value` to a string. An empty string is returned for `null` * and `undefined` values. The sign of `-0` is preserved. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to process. * @returns {string} Returns the string. * @example * * _.toString(null); * // => '' * * _.toString(-0); * // => '-0' * * _.toString([1, 2, 3]); * // => '1,2,3' */ function toString(value) { return value == null ? '' : baseToString(value); } /** * Converts the first character of `string` to upper case and the remaining * to lower case. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to capitalize. * @returns {string} Returns the capitalized string. * @example * * _.capitalize('FRED'); * // => 'Fred' */ function capitalize(string) { return upperFirst(toString(string).toLowerCase()); } /** * Converts the first character of `string` to upper case. * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the converted string. * @example * * _.upperFirst('fred'); * // => 'Fred' * * _.upperFirst('FRED'); * // => 'FRED' */ var upperFirst = createCaseFirst('toUpperCase'); module.exports = capitalize; /***/ }), /***/ 3465: /***/ (function(module, exports, __webpack_require__) { /* module decorator */ module = __webpack_require__.nmd(module); /** * lodash (Custom Build) * Build: `lodash modularize exports="npm" -o ./` * Copyright jQuery Foundation and other contributors * Released under MIT license * Based on Underscore.js 1.8.3 * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors */ /** Used as the size to enable large array optimizations. */ var LARGE_ARRAY_SIZE = 200; /** Used to stand-in for `undefined` hash values. */ var HASH_UNDEFINED = '__lodash_hash_undefined__'; /** Used as references for various `Number` constants. */ var MAX_SAFE_INTEGER = 9007199254740991; /** `Object#toString` result references. */ var argsTag = '[object Arguments]', arrayTag = '[object Array]', boolTag = '[object Boolean]', dateTag = '[object Date]', errorTag = '[object Error]', funcTag = '[object Function]', genTag = '[object GeneratorFunction]', mapTag = '[object Map]', numberTag = '[object Number]', objectTag = '[object Object]', promiseTag = '[object Promise]', regexpTag = '[object RegExp]', setTag = '[object Set]', stringTag = '[object String]', symbolTag = '[object Symbol]', weakMapTag = '[object WeakMap]'; var arrayBufferTag = '[object ArrayBuffer]', dataViewTag = '[object DataView]', float32Tag = '[object Float32Array]', float64Tag = '[object Float64Array]', int8Tag = '[object Int8Array]', int16Tag = '[object Int16Array]', int32Tag = '[object Int32Array]', uint8Tag = '[object Uint8Array]', uint8ClampedTag = '[object Uint8ClampedArray]', uint16Tag = '[object Uint16Array]', uint32Tag = '[object Uint32Array]'; /** * Used to match `RegExp` * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). */ var reRegExpChar = /[\\^$.*+?()[\]{}|]/g; /** Used to match `RegExp` flags from their coerced string values. */ var reFlags = /\w*$/; /** Used to detect host constructors (Safari). */ var reIsHostCtor = /^\[object .+?Constructor\]$/; /** Used to detect unsigned integer values. */ var reIsUint = /^(?:0|[1-9]\d*)$/; /** Used to identify `toStringTag` values supported by `_.clone`. */ var cloneableTags = {}; cloneableTags[argsTag] = cloneableTags[arrayTag] = cloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] = cloneableTags[boolTag] = cloneableTags[dateTag] = cloneableTags[float32Tag] = cloneableTags[float64Tag] = cloneableTags[int8Tag] = cloneableTags[int16Tag] = cloneableTags[int32Tag] = cloneableTags[mapTag] = cloneableTags[numberTag] = cloneableTags[objectTag] = cloneableTags[regexpTag] = cloneableTags[setTag] = cloneableTags[stringTag] = cloneableTags[symbolTag] = cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] = cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true; cloneableTags[errorTag] = cloneableTags[funcTag] = cloneableTags[weakMapTag] = false; /** Detect free variable `global` from Node.js. */ var freeGlobal = typeof __webpack_require__.g == 'object' && __webpack_require__.g && __webpack_require__.g.Object === Object && __webpack_require__.g; /** Detect free variable `self`. */ var freeSelf = typeof self == 'object' && self && self.Object === Object && self; /** Used as a reference to the global object. */ var root = freeGlobal || freeSelf || Function('return this')(); /** Detect free variable `exports`. */ var freeExports = true && exports && !exports.nodeType && exports; /** Detect free variable `module`. */ var freeModule = freeExports && "object" == 'object' && module && !module.nodeType && module; /** Detect the popular CommonJS extension `module.exports`. */ var moduleExports = freeModule && freeModule.exports === freeExports; /** * Adds the key-value `pair` to `map`. * * @private * @param {Object} map The map to modify. * @param {Array} pair The key-value pair to add. * @returns {Object} Returns `map`. */ function addMapEntry(map, pair) { // Don't return `map.set` because it's not chainable in IE 11. map.set(pair[0], pair[1]); return map; } /** * Adds `value` to `set`. * * @private * @param {Object} set The set to modify. * @param {*} value The value to add. * @returns {Object} Returns `set`. */ function addSetEntry(set, value) { // Don't return `set.add` because it's not chainable in IE 11. set.add(value); return set; } /** * A specialized version of `_.forEach` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns `array`. */ function arrayEach(array, iteratee) { var index = -1, length = array ? array.length : 0; while (++index < length) { if (iteratee(array[index], index, array) === false) { break; } } return array; } /** * Appends the elements of `values` to `array`. * * @private * @param {Array} array The array to modify. * @param {Array} values The values to append. * @returns {Array} Returns `array`. */ function arrayPush(array, values) { var index = -1, length = values.length, offset = array.length; while (++index < length) { array[offset + index] = values[index]; } return array; } /** * A specialized version of `_.reduce` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {*} [accumulator] The initial value. * @param {boolean} [initAccum] Specify using the first element of `array` as * the initial value. * @returns {*} Returns the accumulated value. */ function arrayReduce(array, iteratee, accumulator, initAccum) { var index = -1, length = array ? array.length : 0; if (initAccum && length) { accumulator = array[++index]; } while (++index < length) { accumulator = iteratee(accumulator, array[index], index, array); } return accumulator; } /** * The base implementation of `_.times` without support for iteratee shorthands * or max array length checks. * * @private * @param {number} n The number of times to invoke `iteratee`. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns the array of results. */ function baseTimes(n, iteratee) { var index = -1, result = Array(n); while (++index < n) { result[index] = iteratee(index); } return result; } /** * Gets the value at `key` of `object`. * * @private * @param {Object} [object] The object to query. * @param {string} key The key of the property to get. * @returns {*} Returns the property value. */ function getValue(object, key) { return object == null ? undefined : object[key]; } /** * Checks if `value` is a host object in IE < 9. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a host object, else `false`. */ function isHostObject(value) { // Many host objects are `Object` objects that can coerce to strings // despite having improperly defined `toString` methods. var result = false; if (value != null && typeof value.toString != 'function') { try { result = !!(value + ''); } catch (e) {} } return result; } /** * Converts `map` to its key-value pairs. * * @private * @param {Object} map The map to convert. * @returns {Array} Returns the key-value pairs. */ function mapToArray(map) { var index = -1, result = Array(map.size); map.forEach(function(value, key) { result[++index] = [key, value]; }); return result; } /** * Creates a unary function that invokes `func` with its argument transformed. * * @private * @param {Function} func The function to wrap. * @param {Function} transform The argument transform. * @returns {Function} Returns the new function. */ function overArg(func, transform) { return function(arg) { return func(transform(arg)); }; } /** * Converts `set` to an array of its values. * * @private * @param {Object} set The set to convert. * @returns {Array} Returns the values. */ function setToArray(set) { var index = -1, result = Array(set.size); set.forEach(function(value) { result[++index] = value; }); return result; } /** Used for built-in method references. */ var arrayProto = Array.prototype, funcProto = Function.prototype, objectProto = Object.prototype; /** Used to detect overreaching core-js shims. */ var coreJsData = root['__core-js_shared__']; /** Used to detect methods masquerading as native. */ var maskSrcKey = (function() { var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ''); return uid ? ('Symbol(src)_1.' + uid) : ''; }()); /** Used to resolve the decompiled source of functions. */ var funcToString = funcProto.toString; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) * of values. */ var objectToString = objectProto.toString; /** Used to detect if a method is native. */ var reIsNative = RegExp('^' + funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&') .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' ); /** Built-in value references. */ var Buffer = moduleExports ? root.Buffer : undefined, Symbol = root.Symbol, Uint8Array = root.Uint8Array, getPrototype = overArg(Object.getPrototypeOf, Object), objectCreate = Object.create, propertyIsEnumerable = objectProto.propertyIsEnumerable, splice = arrayProto.splice; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeGetSymbols = Object.getOwnPropertySymbols, nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined, nativeKeys = overArg(Object.keys, Object); /* Built-in method references that are verified to be native. */ var DataView = getNative(root, 'DataView'), Map = getNative(root, 'Map'), Promise = getNative(root, 'Promise'), Set = getNative(root, 'Set'), WeakMap = getNative(root, 'WeakMap'), nativeCreate = getNative(Object, 'create'); /** Used to detect maps, sets, and weakmaps. */ var dataViewCtorString = toSource(DataView), mapCtorString = toSource(Map), promiseCtorString = toSource(Promise), setCtorString = toSource(Set), weakMapCtorString = toSource(WeakMap); /** Used to convert symbols to primitives and strings. */ var symbolProto = Symbol ? Symbol.prototype : undefined, symbolValueOf = symbolProto ? symbolProto.valueOf : undefined; /** * Creates a hash object. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function Hash(entries) { var index = -1, length = entries ? entries.length : 0; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } /** * Removes all key-value entries from the hash. * * @private * @name clear * @memberOf Hash */ function hashClear() { this.__data__ = nativeCreate ? nativeCreate(null) : {}; } /** * Removes `key` and its value from the hash. * * @private * @name delete * @memberOf Hash * @param {Object} hash The hash to modify. * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function hashDelete(key) { return this.has(key) && delete this.__data__[key]; } /** * Gets the hash value for `key`. * * @private * @name get * @memberOf Hash * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function hashGet(key) { var data = this.__data__; if (nativeCreate) { var result = data[key]; return result === HASH_UNDEFINED ? undefined : result; } return hasOwnProperty.call(data, key) ? data[key] : undefined; } /** * Checks if a hash value for `key` exists. * * @private * @name has * @memberOf Hash * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function hashHas(key) { var data = this.__data__; return nativeCreate ? data[key] !== undefined : hasOwnProperty.call(data, key); } /** * Sets the hash `key` to `value`. * * @private * @name set * @memberOf Hash * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the hash instance. */ function hashSet(key, value) { var data = this.__data__; data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value; return this; } // Add methods to `Hash`. Hash.prototype.clear = hashClear; Hash.prototype['delete'] = hashDelete; Hash.prototype.get = hashGet; Hash.prototype.has = hashHas; Hash.prototype.set = hashSet; /** * Creates an list cache object. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function ListCache(entries) { var index = -1, length = entries ? entries.length : 0; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } /** * Removes all key-value entries from the list cache. * * @private * @name clear * @memberOf ListCache */ function listCacheClear() { this.__data__ = []; } /** * Removes `key` and its value from the list cache. * * @private * @name delete * @memberOf ListCache * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function listCacheDelete(key) { var data = this.__data__, index = assocIndexOf(data, key); if (index < 0) { return false; } var lastIndex = data.length - 1; if (index == lastIndex) { data.pop(); } else { splice.call(data, index, 1); } return true; } /** * Gets the list cache value for `key`. * * @private * @name get * @memberOf ListCache * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function listCacheGet(key) { var data = this.__data__, index = assocIndexOf(data, key); return index < 0 ? undefined : data[index][1]; } /** * Checks if a list cache value for `key` exists. * * @private * @name has * @memberOf ListCache * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function listCacheHas(key) { return assocIndexOf(this.__data__, key) > -1; } /** * Sets the list cache `key` to `value`. * * @private * @name set * @memberOf ListCache * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the list cache instance. */ function listCacheSet(key, value) { var data = this.__data__, index = assocIndexOf(data, key); if (index < 0) { data.push([key, value]); } else { data[index][1] = value; } return this; } // Add methods to `ListCache`. ListCache.prototype.clear = listCacheClear; ListCache.prototype['delete'] = listCacheDelete; ListCache.prototype.get = listCacheGet; ListCache.prototype.has = listCacheHas; ListCache.prototype.set = listCacheSet; /** * Creates a map cache object to store key-value pairs. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function MapCache(entries) { var index = -1, length = entries ? entries.length : 0; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } /** * Removes all key-value entries from the map. * * @private * @name clear * @memberOf MapCache */ function mapCacheClear() { this.__data__ = { 'hash': new Hash, 'map': new (Map || ListCache), 'string': new Hash }; } /** * Removes `key` and its value from the map. * * @private * @name delete * @memberOf MapCache * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function mapCacheDelete(key) { return getMapData(this, key)['delete'](key); } /** * Gets the map value for `key`. * * @private * @name get * @memberOf MapCache * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function mapCacheGet(key) { return getMapData(this, key).get(key); } /** * Checks if a map value for `key` exists. * * @private * @name has * @memberOf MapCache * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function mapCacheHas(key) { return getMapData(this, key).has(key); } /** * Sets the map `key` to `value`. * * @private * @name set * @memberOf MapCache * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the map cache instance. */ function mapCacheSet(key, value) { getMapData(this, key).set(key, value); return this; } // Add methods to `MapCache`. MapCache.prototype.clear = mapCacheClear; MapCache.prototype['delete'] = mapCacheDelete; MapCache.prototype.get = mapCacheGet; MapCache.prototype.has = mapCacheHas; MapCache.prototype.set = mapCacheSet; /** * Creates a stack cache object to store key-value pairs. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function Stack(entries) { this.__data__ = new ListCache(entries); } /** * Removes all key-value entries from the stack. * * @private * @name clear * @memberOf Stack */ function stackClear() { this.__data__ = new ListCache; } /** * Removes `key` and its value from the stack. * * @private * @name delete * @memberOf Stack * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function stackDelete(key) { return this.__data__['delete'](key); } /** * Gets the stack value for `key`. * * @private * @name get * @memberOf Stack * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function stackGet(key) { return this.__data__.get(key); } /** * Checks if a stack value for `key` exists. * * @private * @name has * @memberOf Stack * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function stackHas(key) { return this.__data__.has(key); } /** * Sets the stack `key` to `value`. * * @private * @name set * @memberOf Stack * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the stack cache instance. */ function stackSet(key, value) { var cache = this.__data__; if (cache instanceof ListCache) { var pairs = cache.__data__; if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) { pairs.push([key, value]); return this; } cache = this.__data__ = new MapCache(pairs); } cache.set(key, value); return this; } // Add methods to `Stack`. Stack.prototype.clear = stackClear; Stack.prototype['delete'] = stackDelete; Stack.prototype.get = stackGet; Stack.prototype.has = stackHas; Stack.prototype.set = stackSet; /** * Creates an array of the enumerable property names of the array-like `value`. * * @private * @param {*} value The value to query. * @param {boolean} inherited Specify returning inherited property names. * @returns {Array} Returns the array of property names. */ function arrayLikeKeys(value, inherited) { // Safari 8.1 makes `arguments.callee` enumerable in strict mode. // Safari 9 makes `arguments.length` enumerable in strict mode. var result = (isArray(value) || isArguments(value)) ? baseTimes(value.length, String) : []; var length = result.length, skipIndexes = !!length; for (var key in value) { if ((inherited || hasOwnProperty.call(value, key)) && !(skipIndexes && (key == 'length' || isIndex(key, length)))) { result.push(key); } } return result; } /** * Assigns `value` to `key` of `object` if the existing value is not equivalent * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. * * @private * @param {Object} object The object to modify. * @param {string} key The key of the property to assign. * @param {*} value The value to assign. */ function assignValue(object, key, value) { var objValue = object[key]; if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) || (value === undefined && !(key in object))) { object[key] = value; } } /** * Gets the index at which the `key` is found in `array` of key-value pairs. * * @private * @param {Array} array The array to inspect. * @param {*} key The key to search for. * @returns {number} Returns the index of the matched value, else `-1`. */ function assocIndexOf(array, key) { var length = array.length; while (length--) { if (eq(array[length][0], key)) { return length; } } return -1; } /** * The base implementation of `_.assign` without support for multiple sources * or `customizer` functions. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @returns {Object} Returns `object`. */ function baseAssign(object, source) { return object && copyObject(source, keys(source), object); } /** * The base implementation of `_.clone` and `_.cloneDeep` which tracks * traversed objects. * * @private * @param {*} value The value to clone. * @param {boolean} [isDeep] Specify a deep clone. * @param {boolean} [isFull] Specify a clone including symbols. * @param {Function} [customizer] The function to customize cloning. * @param {string} [key] The key of `value`. * @param {Object} [object] The parent object of `value`. * @param {Object} [stack] Tracks traversed objects and their clone counterparts. * @returns {*} Returns the cloned value. */ function baseClone(value, isDeep, isFull, customizer, key, object, stack) { var result; if (customizer) { result = object ? customizer(value, key, object, stack) : customizer(value); } if (result !== undefined) { return result; } if (!isObject(value)) { return value; } var isArr = isArray(value); if (isArr) { result = initCloneArray(value); if (!isDeep) { return copyArray(value, result); } } else { var tag = getTag(value), isFunc = tag == funcTag || tag == genTag; if (isBuffer(value)) { return cloneBuffer(value, isDeep); } if (tag == objectTag || tag == argsTag || (isFunc && !object)) { if (isHostObject(value)) { return object ? value : {}; } result = initCloneObject(isFunc ? {} : value); if (!isDeep) { return copySymbols(value, baseAssign(result, value)); } } else { if (!cloneableTags[tag]) { return object ? value : {}; } result = initCloneByTag(value, tag, baseClone, isDeep); } } // Check for circular references and return its corresponding clone. stack || (stack = new Stack); var stacked = stack.get(value); if (stacked) { return stacked; } stack.set(value, result); if (!isArr) { var props = isFull ? getAllKeys(value) : keys(value); } arrayEach(props || value, function(subValue, key) { if (props) { key = subValue; subValue = value[key]; } // Recursively populate clone (susceptible to call stack limits). assignValue(result, key, baseClone(subValue, isDeep, isFull, customizer, key, value, stack)); }); return result; } /** * The base implementation of `_.create` without support for assigning * properties to the created object. * * @private * @param {Object} prototype The object to inherit from. * @returns {Object} Returns the new object. */ function baseCreate(proto) { return isObject(proto) ? objectCreate(proto) : {}; } /** * The base implementation of `getAllKeys` and `getAllKeysIn` which uses * `keysFunc` and `symbolsFunc` to get the enumerable property names and * symbols of `object`. * * @private * @param {Object} object The object to query. * @param {Function} keysFunc The function to get the keys of `object`. * @param {Function} symbolsFunc The function to get the symbols of `object`. * @returns {Array} Returns the array of property names and symbols. */ function baseGetAllKeys(object, keysFunc, symbolsFunc) { var result = keysFunc(object); return isArray(object) ? result : arrayPush(result, symbolsFunc(object)); } /** * The base implementation of `getTag`. * * @private * @param {*} value The value to query. * @returns {string} Returns the `toStringTag`. */ function baseGetTag(value) { return objectToString.call(value); } /** * The base implementation of `_.isNative` without bad shim checks. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a native function, * else `false`. */ function baseIsNative(value) { if (!isObject(value) || isMasked(value)) { return false; } var pattern = (isFunction(value) || isHostObject(value)) ? reIsNative : reIsHostCtor; return pattern.test(toSource(value)); } /** * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. */ function baseKeys(object) { if (!isPrototype(object)) { return nativeKeys(object); } var result = []; for (var key in Object(object)) { if (hasOwnProperty.call(object, key) && key != 'constructor') { result.push(key); } } return result; } /** * Creates a clone of `buffer`. * * @private * @param {Buffer} buffer The buffer to clone. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Buffer} Returns the cloned buffer. */ function cloneBuffer(buffer, isDeep) { if (isDeep) { return buffer.slice(); } var result = new buffer.constructor(buffer.length); buffer.copy(result); return result; } /** * Creates a clone of `arrayBuffer`. * * @private * @param {ArrayBuffer} arrayBuffer The array buffer to clone. * @returns {ArrayBuffer} Returns the cloned array buffer. */ function cloneArrayBuffer(arrayBuffer) { var result = new arrayBuffer.constructor(arrayBuffer.byteLength); new Uint8Array(result).set(new Uint8Array(arrayBuffer)); return result; } /** * Creates a clone of `dataView`. * * @private * @param {Object} dataView The data view to clone. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Object} Returns the cloned data view. */ function cloneDataView(dataView, isDeep) { var buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer; return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength); } /** * Creates a clone of `map`. * * @private * @param {Object} map The map to clone. * @param {Function} cloneFunc The function to clone values. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Object} Returns the cloned map. */ function cloneMap(map, isDeep, cloneFunc) { var array = isDeep ? cloneFunc(mapToArray(map), true) : mapToArray(map); return arrayReduce(array, addMapEntry, new map.constructor); } /** * Creates a clone of `regexp`. * * @private * @param {Object} regexp The regexp to clone. * @returns {Object} Returns the cloned regexp. */ function cloneRegExp(regexp) { var result = new regexp.constructor(regexp.source, reFlags.exec(regexp)); result.lastIndex = regexp.lastIndex; return result; } /** * Creates a clone of `set`. * * @private * @param {Object} set The set to clone. * @param {Function} cloneFunc The function to clone values. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Object} Returns the cloned set. */ function cloneSet(set, isDeep, cloneFunc) { var array = isDeep ? cloneFunc(setToArray(set), true) : setToArray(set); return arrayReduce(array, addSetEntry, new set.constructor); } /** * Creates a clone of the `symbol` object. * * @private * @param {Object} symbol The symbol object to clone. * @returns {Object} Returns the cloned symbol object. */ function cloneSymbol(symbol) { return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {}; } /** * Creates a clone of `typedArray`. * * @private * @param {Object} typedArray The typed array to clone. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Object} Returns the cloned typed array. */ function cloneTypedArray(typedArray, isDeep) { var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer; return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length); } /** * Copies the values of `source` to `array`. * * @private * @param {Array} source The array to copy values from. * @param {Array} [array=[]] The array to copy values to. * @returns {Array} Returns `array`. */ function copyArray(source, array) { var index = -1, length = source.length; array || (array = Array(length)); while (++index < length) { array[index] = source[index]; } return array; } /** * Copies properties of `source` to `object`. * * @private * @param {Object} source The object to copy properties from. * @param {Array} props The property identifiers to copy. * @param {Object} [object={}] The object to copy properties to. * @param {Function} [customizer] The function to customize copied values. * @returns {Object} Returns `object`. */ function copyObject(source, props, object, customizer) { object || (object = {}); var index = -1, length = props.length; while (++index < length) { var key = props[index]; var newValue = customizer ? customizer(object[key], source[key], key, object, source) : undefined; assignValue(object, key, newValue === undefined ? source[key] : newValue); } return object; } /** * Copies own symbol properties of `source` to `object`. * * @private * @param {Object} source The object to copy symbols from. * @param {Object} [object={}] The object to copy symbols to. * @returns {Object} Returns `object`. */ function copySymbols(source, object) { return copyObject(source, getSymbols(source), object); } /** * Creates an array of own enumerable property names and symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names and symbols. */ function getAllKeys(object) { return baseGetAllKeys(object, keys, getSymbols); } /** * Gets the data for `map`. * * @private * @param {Object} map The map to query. * @param {string} key The reference key. * @returns {*} Returns the map data. */ function getMapData(map, key) { var data = map.__data__; return isKeyable(key) ? data[typeof key == 'string' ? 'string' : 'hash'] : data.map; } /** * Gets the native function at `key` of `object`. * * @private * @param {Object} object The object to query. * @param {string} key The key of the method to get. * @returns {*} Returns the function if it's native, else `undefined`. */ function getNative(object, key) { var value = getValue(object, key); return baseIsNative(value) ? value : undefined; } /** * Creates an array of the own enumerable symbol properties of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of symbols. */ var getSymbols = nativeGetSymbols ? overArg(nativeGetSymbols, Object) : stubArray; /** * Gets the `toStringTag` of `value`. * * @private * @param {*} value The value to query. * @returns {string} Returns the `toStringTag`. */ var getTag = baseGetTag; // Fallback for data views, maps, sets, and weak maps in IE 11, // for data views in Edge < 14, and promises in Node.js. if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) || (Map && getTag(new Map) != mapTag) || (Promise && getTag(Promise.resolve()) != promiseTag) || (Set && getTag(new Set) != setTag) || (WeakMap && getTag(new WeakMap) != weakMapTag)) { getTag = function(value) { var result = objectToString.call(value), Ctor = result == objectTag ? value.constructor : undefined, ctorString = Ctor ? toSource(Ctor) : undefined; if (ctorString) { switch (ctorString) { case dataViewCtorString: return dataViewTag; case mapCtorString: return mapTag; case promiseCtorString: return promiseTag; case setCtorString: return setTag; case weakMapCtorString: return weakMapTag; } } return result; }; } /** * Initializes an array clone. * * @private * @param {Array} array The array to clone. * @returns {Array} Returns the initialized clone. */ function initCloneArray(array) { var length = array.length, result = array.constructor(length); // Add properties assigned by `RegExp#exec`. if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) { result.index = array.index; result.input = array.input; } return result; } /** * Initializes an object clone. * * @private * @param {Object} object The object to clone. * @returns {Object} Returns the initialized clone. */ function initCloneObject(object) { return (typeof object.constructor == 'function' && !isPrototype(object)) ? baseCreate(getPrototype(object)) : {}; } /** * Initializes an object clone based on its `toStringTag`. * * **Note:** This function only supports cloning values with tags of * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. * * @private * @param {Object} object The object to clone. * @param {string} tag The `toStringTag` of the object to clone. * @param {Function} cloneFunc The function to clone values. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Object} Returns the initialized clone. */ function initCloneByTag(object, tag, cloneFunc, isDeep) { var Ctor = object.constructor; switch (tag) { case arrayBufferTag: return cloneArrayBuffer(object); case boolTag: case dateTag: return new Ctor(+object); case dataViewTag: return cloneDataView(object, isDeep); case float32Tag: case float64Tag: case int8Tag: case int16Tag: case int32Tag: case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag: return cloneTypedArray(object, isDeep); case mapTag: return cloneMap(object, isDeep, cloneFunc); case numberTag: case stringTag: return new Ctor(object); case regexpTag: return cloneRegExp(object); case setTag: return cloneSet(object, isDeep, cloneFunc); case symbolTag: return cloneSymbol(object); } } /** * Checks if `value` is a valid array-like index. * * @private * @param {*} value The value to check. * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. */ function isIndex(value, length) { length = length == null ? MAX_SAFE_INTEGER : length; return !!length && (typeof value == 'number' || reIsUint.test(value)) && (value > -1 && value % 1 == 0 && value < length); } /** * Checks if `value` is suitable for use as unique object key. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is suitable, else `false`. */ function isKeyable(value) { var type = typeof value; return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean') ? (value !== '__proto__') : (value === null); } /** * Checks if `func` has its source masked. * * @private * @param {Function} func The function to check. * @returns {boolean} Returns `true` if `func` is masked, else `false`. */ function isMasked(func) { return !!maskSrcKey && (maskSrcKey in func); } /** * Checks if `value` is likely a prototype object. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. */ function isPrototype(value) { var Ctor = value && value.constructor, proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto; return value === proto; } /** * Converts `func` to its source code. * * @private * @param {Function} func The function to process. * @returns {string} Returns the source code. */ function toSource(func) { if (func != null) { try { return funcToString.call(func); } catch (e) {} try { return (func + ''); } catch (e) {} } return ''; } /** * This method is like `_.clone` except that it recursively clones `value`. * * @static * @memberOf _ * @since 1.0.0 * @category Lang * @param {*} value The value to recursively clone. * @returns {*} Returns the deep cloned value. * @see _.clone * @example * * var objects = [{ 'a': 1 }, { 'b': 2 }]; * * var deep = _.cloneDeep(objects); * console.log(deep[0] === objects[0]); * // => false */ function cloneDeep(value) { return baseClone(value, true, true); } /** * Performs a * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * comparison between two values to determine if they are equivalent. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. * @example * * var object = { 'a': 1 }; * var other = { 'a': 1 }; * * _.eq(object, object); * // => true * * _.eq(object, other); * // => false * * _.eq('a', 'a'); * // => true * * _.eq('a', Object('a')); * // => false * * _.eq(NaN, NaN); * // => true */ function eq(value, other) { return value === other || (value !== value && other !== other); } /** * Checks if `value` is likely an `arguments` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an `arguments` object, * else `false`. * @example * * _.isArguments(function() { return arguments; }()); * // => true * * _.isArguments([1, 2, 3]); * // => false */ function isArguments(value) { // Safari 8.1 makes `arguments.callee` enumerable in strict mode. return isArrayLikeObject(value) && hasOwnProperty.call(value, 'callee') && (!propertyIsEnumerable.call(value, 'callee') || objectToString.call(value) == argsTag); } /** * Checks if `value` is classified as an `Array` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an array, else `false`. * @example * * _.isArray([1, 2, 3]); * // => true * * _.isArray(document.body.children); * // => false * * _.isArray('abc'); * // => false * * _.isArray(_.noop); * // => false */ var isArray = Array.isArray; /** * Checks if `value` is array-like. A value is considered array-like if it's * not a function and has a `value.length` that's an integer greater than or * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is array-like, else `false`. * @example * * _.isArrayLike([1, 2, 3]); * // => true * * _.isArrayLike(document.body.children); * // => true * * _.isArrayLike('abc'); * // => true * * _.isArrayLike(_.noop); * // => false */ function isArrayLike(value) { return value != null && isLength(value.length) && !isFunction(value); } /** * This method is like `_.isArrayLike` except that it also checks if `value` * is an object. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an array-like object, * else `false`. * @example * * _.isArrayLikeObject([1, 2, 3]); * // => true * * _.isArrayLikeObject(document.body.children); * // => true * * _.isArrayLikeObject('abc'); * // => false * * _.isArrayLikeObject(_.noop); * // => false */ function isArrayLikeObject(value) { return isObjectLike(value) && isArrayLike(value); } /** * Checks if `value` is a buffer. * * @static * @memberOf _ * @since 4.3.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a buffer, else `false`. * @example * * _.isBuffer(new Buffer(2)); * // => true * * _.isBuffer(new Uint8Array(2)); * // => false */ var isBuffer = nativeIsBuffer || stubFalse; /** * Checks if `value` is classified as a `Function` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a function, else `false`. * @example * * _.isFunction(_); * // => true * * _.isFunction(/abc/); * // => false */ function isFunction(value) { // The use of `Object#toString` avoids issues with the `typeof` operator // in Safari 8-9 which returns 'object' for typed array and other constructors. var tag = isObject(value) ? objectToString.call(value) : ''; return tag == funcTag || tag == genTag; } /** * Checks if `value` is a valid array-like length. * * **Note:** This method is loosely based on * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. * @example * * _.isLength(3); * // => true * * _.isLength(Number.MIN_VALUE); * // => false * * _.isLength(Infinity); * // => false * * _.isLength('3'); * // => false */ function isLength(value) { return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; } /** * Checks if `value` is the * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an object, else `false`. * @example * * _.isObject({}); * // => true * * _.isObject([1, 2, 3]); * // => true * * _.isObject(_.noop); * // => true * * _.isObject(null); * // => false */ function isObject(value) { var type = typeof value; return !!value && (type == 'object' || type == 'function'); } /** * Checks if `value` is object-like. A value is object-like if it's not `null` * and has a `typeof` result of "object". * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is object-like, else `false`. * @example * * _.isObjectLike({}); * // => true * * _.isObjectLike([1, 2, 3]); * // => true * * _.isObjectLike(_.noop); * // => false * * _.isObjectLike(null); * // => false */ function isObjectLike(value) { return !!value && typeof value == 'object'; } /** * Creates an array of the own enumerable property names of `object`. * * **Note:** Non-object values are coerced to objects. See the * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) * for more details. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.keys(new Foo); * // => ['a', 'b'] (iteration order is not guaranteed) * * _.keys('hi'); * // => ['0', '1'] */ function keys(object) { return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object); } /** * This method returns a new empty array. * * @static * @memberOf _ * @since 4.13.0 * @category Util * @returns {Array} Returns the new empty array. * @example * * var arrays = _.times(2, _.stubArray); * * console.log(arrays); * // => [[], []] * * console.log(arrays[0] === arrays[1]); * // => false */ function stubArray() { return []; } /** * This method returns `false`. * * @static * @memberOf _ * @since 4.13.0 * @category Util * @returns {boolean} Returns `false`. * @example * * _.times(2, _.stubFalse); * // => [false, false] */ function stubFalse() { return false; } module.exports = cloneDeep; /***/ }), /***/ 1296: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { /** * lodash (Custom Build) * Build: `lodash modularize exports="npm" -o ./` * Copyright jQuery Foundation and other contributors * Released under MIT license * Based on Underscore.js 1.8.3 * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors */ /** Used as the `TypeError` message for "Functions" methods. */ var FUNC_ERROR_TEXT = 'Expected a function'; /** Used as references for various `Number` constants. */ var NAN = 0 / 0; /** `Object#toString` result references. */ var symbolTag = '[object Symbol]'; /** Used to match leading and trailing whitespace. */ var reTrim = /^\s+|\s+$/g; /** Used to detect bad signed hexadecimal string values. */ var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; /** Used to detect binary string values. */ var reIsBinary = /^0b[01]+$/i; /** Used to detect octal string values. */ var reIsOctal = /^0o[0-7]+$/i; /** Built-in method references without a dependency on `root`. */ var freeParseInt = parseInt; /** Detect free variable `global` from Node.js. */ var freeGlobal = typeof __webpack_require__.g == 'object' && __webpack_require__.g && __webpack_require__.g.Object === Object && __webpack_require__.g; /** Detect free variable `self`. */ var freeSelf = typeof self == 'object' && self && self.Object === Object && self; /** Used as a reference to the global object. */ var root = freeGlobal || freeSelf || Function('return this')(); /** Used for built-in method references. */ var objectProto = Object.prototype; /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) * of values. */ var objectToString = objectProto.toString; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMax = Math.max, nativeMin = Math.min; /** * Gets the timestamp of the number of milliseconds that have elapsed since * the Unix epoch (1 January 1970 00:00:00 UTC). * * @static * @memberOf _ * @since 2.4.0 * @category Date * @returns {number} Returns the timestamp. * @example * * _.defer(function(stamp) { * console.log(_.now() - stamp); * }, _.now()); * // => Logs the number of milliseconds it took for the deferred invocation. */ var now = function() { return root.Date.now(); }; /** * Creates a debounced function that delays invoking `func` until after `wait` * milliseconds have elapsed since the last time the debounced function was * invoked. The debounced function comes with a `cancel` method to cancel * delayed `func` invocations and a `flush` method to immediately invoke them. * Provide `options` to indicate whether `func` should be invoked on the * leading and/or trailing edge of the `wait` timeout. The `func` is invoked * with the last arguments provided to the debounced function. Subsequent * calls to the debounced function return the result of the last `func` * invocation. * * **Note:** If `leading` and `trailing` options are `true`, `func` is * invoked on the trailing edge of the timeout only if the debounced function * is invoked more than once during the `wait` timeout. * * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred * until to the next tick, similar to `setTimeout` with a timeout of `0`. * * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/) * for details over the differences between `_.debounce` and `_.throttle`. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to debounce. * @param {number} [wait=0] The number of milliseconds to delay. * @param {Object} [options={}] The options object. * @param {boolean} [options.leading=false] * Specify invoking on the leading edge of the timeout. * @param {number} [options.maxWait] * The maximum time `func` is allowed to be delayed before it's invoked. * @param {boolean} [options.trailing=true] * Specify invoking on the trailing edge of the timeout. * @returns {Function} Returns the new debounced function. * @example * * // Avoid costly calculations while the window size is in flux. * jQuery(window).on('resize', _.debounce(calculateLayout, 150)); * * // Invoke `sendMail` when clicked, debouncing subsequent calls. * jQuery(element).on('click', _.debounce(sendMail, 300, { * 'leading': true, * 'trailing': false * })); * * // Ensure `batchLog` is invoked once after 1 second of debounced calls. * var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 }); * var source = new EventSource('/stream'); * jQuery(source).on('message', debounced); * * // Cancel the trailing debounced invocation. * jQuery(window).on('popstate', debounced.cancel); */ function debounce(func, wait, options) { var lastArgs, lastThis, maxWait, result, timerId, lastCallTime, lastInvokeTime = 0, leading = false, maxing = false, trailing = true; if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } wait = toNumber(wait) || 0; if (isObject(options)) { leading = !!options.leading; maxing = 'maxWait' in options; maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait; trailing = 'trailing' in options ? !!options.trailing : trailing; } function invokeFunc(time) { var args = lastArgs, thisArg = lastThis; lastArgs = lastThis = undefined; lastInvokeTime = time; result = func.apply(thisArg, args); return result; } function leadingEdge(time) { // Reset any `maxWait` timer. lastInvokeTime = time; // Start the timer for the trailing edge. timerId = setTimeout(timerExpired, wait); // Invoke the leading edge. return leading ? invokeFunc(time) : result; } function remainingWait(time) { var timeSinceLastCall = time - lastCallTime, timeSinceLastInvoke = time - lastInvokeTime, result = wait - timeSinceLastCall; return maxing ? nativeMin(result, maxWait - timeSinceLastInvoke) : result; } function shouldInvoke(time) { var timeSinceLastCall = time - lastCallTime, timeSinceLastInvoke = time - lastInvokeTime; // Either this is the first call, activity has stopped and we're at the // trailing edge, the system time has gone backwards and we're treating // it as the trailing edge, or we've hit the `maxWait` limit. return (lastCallTime === undefined || (timeSinceLastCall >= wait) || (timeSinceLastCall < 0) || (maxing && timeSinceLastInvoke >= maxWait)); } function timerExpired() { var time = now(); if (shouldInvoke(time)) { return trailingEdge(time); } // Restart the timer. timerId = setTimeout(timerExpired, remainingWait(time)); } function trailingEdge(time) { timerId = undefined; // Only invoke if we have `lastArgs` which means `func` has been // debounced at least once. if (trailing && lastArgs) { return invokeFunc(time); } lastArgs = lastThis = undefined; return result; } function cancel() { if (timerId !== undefined) { clearTimeout(timerId); } lastInvokeTime = 0; lastArgs = lastCallTime = lastThis = timerId = undefined; } function flush() { return timerId === undefined ? result : trailingEdge(now()); } function debounced() { var time = now(), isInvoking = shouldInvoke(time); lastArgs = arguments; lastThis = this; lastCallTime = time; if (isInvoking) { if (timerId === undefined) { return leadingEdge(lastCallTime); } if (maxing) { // Handle invocations in a tight loop. timerId = setTimeout(timerExpired, wait); return invokeFunc(lastCallTime); } } if (timerId === undefined) { timerId = setTimeout(timerExpired, wait); } return result; } debounced.cancel = cancel; debounced.flush = flush; return debounced; } /** * Checks if `value` is the * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an object, else `false`. * @example * * _.isObject({}); * // => true * * _.isObject([1, 2, 3]); * // => true * * _.isObject(_.noop); * // => true * * _.isObject(null); * // => false */ function isObject(value) { var type = typeof value; return !!value && (type == 'object' || type == 'function'); } /** * Checks if `value` is object-like. A value is object-like if it's not `null` * and has a `typeof` result of "object". * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is object-like, else `false`. * @example * * _.isObjectLike({}); * // => true * * _.isObjectLike([1, 2, 3]); * // => true * * _.isObjectLike(_.noop); * // => false * * _.isObjectLike(null); * // => false */ function isObjectLike(value) { return !!value && typeof value == 'object'; } /** * Checks if `value` is classified as a `Symbol` primitive or object. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. * @example * * _.isSymbol(Symbol.iterator); * // => true * * _.isSymbol('abc'); * // => false */ function isSymbol(value) { return typeof value == 'symbol' || (isObjectLike(value) && objectToString.call(value) == symbolTag); } /** * Converts `value` to a number. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to process. * @returns {number} Returns the number. * @example * * _.toNumber(3.2); * // => 3.2 * * _.toNumber(Number.MIN_VALUE); * // => 5e-324 * * _.toNumber(Infinity); * // => Infinity * * _.toNumber('3.2'); * // => 3.2 */ function toNumber(value) { if (typeof value == 'number') { return value; } if (isSymbol(value)) { return NAN; } if (isObject(value)) { var other = typeof value.valueOf == 'function' ? value.valueOf() : value; value = isObject(other) ? (other + '') : other; } if (typeof value != 'string') { return value === 0 ? value : +value; } value = value.replace(reTrim, ''); var isBinary = reIsBinary.test(value); return (isBinary || reIsOctal.test(value)) ? freeParseInt(value.slice(2), isBinary ? 2 : 8) : (reIsBadHex.test(value) ? NAN : +value); } module.exports = debounce; /***/ }), /***/ 9208: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { /** * lodash (Custom Build) * Build: `lodash modularize exports="npm" -o ./` * Copyright jQuery Foundation and other contributors * Released under MIT license * Based on Underscore.js 1.8.3 * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors */ /** Used as the `TypeError` message for "Functions" methods. */ var FUNC_ERROR_TEXT = 'Expected a function'; /** Used to stand-in for `undefined` hash values. */ var HASH_UNDEFINED = '__lodash_hash_undefined__'; /** Used as references for various `Number` constants. */ var INFINITY = 1 / 0; /** `Object#toString` result references. */ var funcTag = '[object Function]', genTag = '[object GeneratorFunction]', symbolTag = '[object Symbol]'; /** Used to match property names within property paths. */ var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/, reIsPlainProp = /^\w*$/, reLeadingDot = /^\./, rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g; /** * Used to match `RegExp` * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). */ var reRegExpChar = /[\\^$.*+?()[\]{}|]/g; /** Used to match backslashes in property paths. */ var reEscapeChar = /\\(\\)?/g; /** Used to detect host constructors (Safari). */ var reIsHostCtor = /^\[object .+?Constructor\]$/; /** Detect free variable `global` from Node.js. */ var freeGlobal = typeof __webpack_require__.g == 'object' && __webpack_require__.g && __webpack_require__.g.Object === Object && __webpack_require__.g; /** Detect free variable `self`. */ var freeSelf = typeof self == 'object' && self && self.Object === Object && self; /** Used as a reference to the global object. */ var root = freeGlobal || freeSelf || Function('return this')(); /** * Gets the value at `key` of `object`. * * @private * @param {Object} [object] The object to query. * @param {string} key The key of the property to get. * @returns {*} Returns the property value. */ function getValue(object, key) { return object == null ? undefined : object[key]; } /** * Checks if `value` is a host object in IE < 9. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a host object, else `false`. */ function isHostObject(value) { // Many host objects are `Object` objects that can coerce to strings // despite having improperly defined `toString` methods. var result = false; if (value != null && typeof value.toString != 'function') { try { result = !!(value + ''); } catch (e) {} } return result; } /** Used for built-in method references. */ var arrayProto = Array.prototype, funcProto = Function.prototype, objectProto = Object.prototype; /** Used to detect overreaching core-js shims. */ var coreJsData = root['__core-js_shared__']; /** Used to detect methods masquerading as native. */ var maskSrcKey = (function() { var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ''); return uid ? ('Symbol(src)_1.' + uid) : ''; }()); /** Used to resolve the decompiled source of functions. */ var funcToString = funcProto.toString; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) * of values. */ var objectToString = objectProto.toString; /** Used to detect if a method is native. */ var reIsNative = RegExp('^' + funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&') .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' ); /** Built-in value references. */ var Symbol = root.Symbol, splice = arrayProto.splice; /* Built-in method references that are verified to be native. */ var Map = getNative(root, 'Map'), nativeCreate = getNative(Object, 'create'); /** Used to convert symbols to primitives and strings. */ var symbolProto = Symbol ? Symbol.prototype : undefined, symbolToString = symbolProto ? symbolProto.toString : undefined; /** * Creates a hash object. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function Hash(entries) { var index = -1, length = entries ? entries.length : 0; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } /** * Removes all key-value entries from the hash. * * @private * @name clear * @memberOf Hash */ function hashClear() { this.__data__ = nativeCreate ? nativeCreate(null) : {}; } /** * Removes `key` and its value from the hash. * * @private * @name delete * @memberOf Hash * @param {Object} hash The hash to modify. * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function hashDelete(key) { return this.has(key) && delete this.__data__[key]; } /** * Gets the hash value for `key`. * * @private * @name get * @memberOf Hash * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function hashGet(key) { var data = this.__data__; if (nativeCreate) { var result = data[key]; return result === HASH_UNDEFINED ? undefined : result; } return hasOwnProperty.call(data, key) ? data[key] : undefined; } /** * Checks if a hash value for `key` exists. * * @private * @name has * @memberOf Hash * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function hashHas(key) { var data = this.__data__; return nativeCreate ? data[key] !== undefined : hasOwnProperty.call(data, key); } /** * Sets the hash `key` to `value`. * * @private * @name set * @memberOf Hash * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the hash instance. */ function hashSet(key, value) { var data = this.__data__; data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value; return this; } // Add methods to `Hash`. Hash.prototype.clear = hashClear; Hash.prototype['delete'] = hashDelete; Hash.prototype.get = hashGet; Hash.prototype.has = hashHas; Hash.prototype.set = hashSet; /** * Creates an list cache object. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function ListCache(entries) { var index = -1, length = entries ? entries.length : 0; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } /** * Removes all key-value entries from the list cache. * * @private * @name clear * @memberOf ListCache */ function listCacheClear() { this.__data__ = []; } /** * Removes `key` and its value from the list cache. * * @private * @name delete * @memberOf ListCache * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function listCacheDelete(key) { var data = this.__data__, index = assocIndexOf(data, key); if (index < 0) { return false; } var lastIndex = data.length - 1; if (index == lastIndex) { data.pop(); } else { splice.call(data, index, 1); } return true; } /** * Gets the list cache value for `key`. * * @private * @name get * @memberOf ListCache * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function listCacheGet(key) { var data = this.__data__, index = assocIndexOf(data, key); return index < 0 ? undefined : data[index][1]; } /** * Checks if a list cache value for `key` exists. * * @private * @name has * @memberOf ListCache * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function listCacheHas(key) { return assocIndexOf(this.__data__, key) > -1; } /** * Sets the list cache `key` to `value`. * * @private * @name set * @memberOf ListCache * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the list cache instance. */ function listCacheSet(key, value) { var data = this.__data__, index = assocIndexOf(data, key); if (index < 0) { data.push([key, value]); } else { data[index][1] = value; } return this; } // Add methods to `ListCache`. ListCache.prototype.clear = listCacheClear; ListCache.prototype['delete'] = listCacheDelete; ListCache.prototype.get = listCacheGet; ListCache.prototype.has = listCacheHas; ListCache.prototype.set = listCacheSet; /** * Creates a map cache object to store key-value pairs. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function MapCache(entries) { var index = -1, length = entries ? entries.length : 0; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } /** * Removes all key-value entries from the map. * * @private * @name clear * @memberOf MapCache */ function mapCacheClear() { this.__data__ = { 'hash': new Hash, 'map': new (Map || ListCache), 'string': new Hash }; } /** * Removes `key` and its value from the map. * * @private * @name delete * @memberOf MapCache * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function mapCacheDelete(key) { return getMapData(this, key)['delete'](key); } /** * Gets the map value for `key`. * * @private * @name get * @memberOf MapCache * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function mapCacheGet(key) { return getMapData(this, key).get(key); } /** * Checks if a map value for `key` exists. * * @private * @name has * @memberOf MapCache * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function mapCacheHas(key) { return getMapData(this, key).has(key); } /** * Sets the map `key` to `value`. * * @private * @name set * @memberOf MapCache * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the map cache instance. */ function mapCacheSet(key, value) { getMapData(this, key).set(key, value); return this; } // Add methods to `MapCache`. MapCache.prototype.clear = mapCacheClear; MapCache.prototype['delete'] = mapCacheDelete; MapCache.prototype.get = mapCacheGet; MapCache.prototype.has = mapCacheHas; MapCache.prototype.set = mapCacheSet; /** * Gets the index at which the `key` is found in `array` of key-value pairs. * * @private * @param {Array} array The array to inspect. * @param {*} key The key to search for. * @returns {number} Returns the index of the matched value, else `-1`. */ function assocIndexOf(array, key) { var length = array.length; while (length--) { if (eq(array[length][0], key)) { return length; } } return -1; } /** * The base implementation of `_.get` without support for default values. * * @private * @param {Object} object The object to query. * @param {Array|string} path The path of the property to get. * @returns {*} Returns the resolved value. */ function baseGet(object, path) { path = isKey(path, object) ? [path] : castPath(path); var index = 0, length = path.length; while (object != null && index < length) { object = object[toKey(path[index++])]; } return (index && index == length) ? object : undefined; } /** * The base implementation of `_.isNative` without bad shim checks. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a native function, * else `false`. */ function baseIsNative(value) { if (!isObject(value) || isMasked(value)) { return false; } var pattern = (isFunction(value) || isHostObject(value)) ? reIsNative : reIsHostCtor; return pattern.test(toSource(value)); } /** * The base implementation of `_.toString` which doesn't convert nullish * values to empty strings. * * @private * @param {*} value The value to process. * @returns {string} Returns the string. */ function baseToString(value) { // Exit early for strings to avoid a performance hit in some environments. if (typeof value == 'string') { return value; } if (isSymbol(value)) { return symbolToString ? symbolToString.call(value) : ''; } var result = (value + ''); return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; } /** * Casts `value` to a path array if it's not one. * * @private * @param {*} value The value to inspect. * @returns {Array} Returns the cast property path array. */ function castPath(value) { return isArray(value) ? value : stringToPath(value); } /** * Gets the data for `map`. * * @private * @param {Object} map The map to query. * @param {string} key The reference key. * @returns {*} Returns the map data. */ function getMapData(map, key) { var data = map.__data__; return isKeyable(key) ? data[typeof key == 'string' ? 'string' : 'hash'] : data.map; } /** * Gets the native function at `key` of `object`. * * @private * @param {Object} object The object to query. * @param {string} key The key of the method to get. * @returns {*} Returns the function if it's native, else `undefined`. */ function getNative(object, key) { var value = getValue(object, key); return baseIsNative(value) ? value : undefined; } /** * Checks if `value` is a property name and not a property path. * * @private * @param {*} value The value to check. * @param {Object} [object] The object to query keys on. * @returns {boolean} Returns `true` if `value` is a property name, else `false`. */ function isKey(value, object) { if (isArray(value)) { return false; } var type = typeof value; if (type == 'number' || type == 'symbol' || type == 'boolean' || value == null || isSymbol(value)) { return true; } return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || (object != null && value in Object(object)); } /** * Checks if `value` is suitable for use as unique object key. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is suitable, else `false`. */ function isKeyable(value) { var type = typeof value; return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean') ? (value !== '__proto__') : (value === null); } /** * Checks if `func` has its source masked. * * @private * @param {Function} func The function to check. * @returns {boolean} Returns `true` if `func` is masked, else `false`. */ function isMasked(func) { return !!maskSrcKey && (maskSrcKey in func); } /** * Converts `string` to a property path array. * * @private * @param {string} string The string to convert. * @returns {Array} Returns the property path array. */ var stringToPath = memoize(function(string) { string = toString(string); var result = []; if (reLeadingDot.test(string)) { result.push(''); } string.replace(rePropName, function(match, number, quote, string) { result.push(quote ? string.replace(reEscapeChar, '$1') : (number || match)); }); return result; }); /** * Converts `value` to a string key if it's not a string or symbol. * * @private * @param {*} value The value to inspect. * @returns {string|symbol} Returns the key. */ function toKey(value) { if (typeof value == 'string' || isSymbol(value)) { return value; } var result = (value + ''); return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; } /** * Converts `func` to its source code. * * @private * @param {Function} func The function to process. * @returns {string} Returns the source code. */ function toSource(func) { if (func != null) { try { return funcToString.call(func); } catch (e) {} try { return (func + ''); } catch (e) {} } return ''; } /** * Creates a function that memoizes the result of `func`. If `resolver` is * provided, it determines the cache key for storing the result based on the * arguments provided to the memoized function. By default, the first argument * provided to the memoized function is used as the map cache key. The `func` * is invoked with the `this` binding of the memoized function. * * **Note:** The cache is exposed as the `cache` property on the memoized * function. Its creation may be customized by replacing the `_.memoize.Cache` * constructor with one whose instances implement the * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object) * method interface of `delete`, `get`, `has`, and `set`. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to have its output memoized. * @param {Function} [resolver] The function to resolve the cache key. * @returns {Function} Returns the new memoized function. * @example * * var object = { 'a': 1, 'b': 2 }; * var other = { 'c': 3, 'd': 4 }; * * var values = _.memoize(_.values); * values(object); * // => [1, 2] * * values(other); * // => [3, 4] * * object.a = 2; * values(object); * // => [1, 2] * * // Modify the result cache. * values.cache.set(object, ['a', 'b']); * values(object); * // => ['a', 'b'] * * // Replace `_.memoize.Cache`. * _.memoize.Cache = WeakMap; */ function memoize(func, resolver) { if (typeof func != 'function' || (resolver && typeof resolver != 'function')) { throw new TypeError(FUNC_ERROR_TEXT); } var memoized = function() { var args = arguments, key = resolver ? resolver.apply(this, args) : args[0], cache = memoized.cache; if (cache.has(key)) { return cache.get(key); } var result = func.apply(this, args); memoized.cache = cache.set(key, result); return result; }; memoized.cache = new (memoize.Cache || MapCache); return memoized; } // Assign cache to `_.memoize`. memoize.Cache = MapCache; /** * Performs a * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * comparison between two values to determine if they are equivalent. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. * @example * * var object = { 'a': 1 }; * var other = { 'a': 1 }; * * _.eq(object, object); * // => true * * _.eq(object, other); * // => false * * _.eq('a', 'a'); * // => true * * _.eq('a', Object('a')); * // => false * * _.eq(NaN, NaN); * // => true */ function eq(value, other) { return value === other || (value !== value && other !== other); } /** * Checks if `value` is classified as an `Array` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an array, else `false`. * @example * * _.isArray([1, 2, 3]); * // => true * * _.isArray(document.body.children); * // => false * * _.isArray('abc'); * // => false * * _.isArray(_.noop); * // => false */ var isArray = Array.isArray; /** * Checks if `value` is classified as a `Function` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a function, else `false`. * @example * * _.isFunction(_); * // => true * * _.isFunction(/abc/); * // => false */ function isFunction(value) { // The use of `Object#toString` avoids issues with the `typeof` operator // in Safari 8-9 which returns 'object' for typed array and other constructors. var tag = isObject(value) ? objectToString.call(value) : ''; return tag == funcTag || tag == genTag; } /** * Checks if `value` is the * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an object, else `false`. * @example * * _.isObject({}); * // => true * * _.isObject([1, 2, 3]); * // => true * * _.isObject(_.noop); * // => true * * _.isObject(null); * // => false */ function isObject(value) { var type = typeof value; return !!value && (type == 'object' || type == 'function'); } /** * Checks if `value` is object-like. A value is object-like if it's not `null` * and has a `typeof` result of "object". * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is object-like, else `false`. * @example * * _.isObjectLike({}); * // => true * * _.isObjectLike([1, 2, 3]); * // => true * * _.isObjectLike(_.noop); * // => false * * _.isObjectLike(null); * // => false */ function isObjectLike(value) { return !!value && typeof value == 'object'; } /** * Checks if `value` is classified as a `Symbol` primitive or object. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. * @example * * _.isSymbol(Symbol.iterator); * // => true * * _.isSymbol('abc'); * // => false */ function isSymbol(value) { return typeof value == 'symbol' || (isObjectLike(value) && objectToString.call(value) == symbolTag); } /** * Converts `value` to a string. An empty string is returned for `null` * and `undefined` values. The sign of `-0` is preserved. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to process. * @returns {string} Returns the string. * @example * * _.toString(null); * // => '' * * _.toString(-0); * // => '-0' * * _.toString([1, 2, 3]); * // => '1,2,3' */ function toString(value) { return value == null ? '' : baseToString(value); } /** * Gets the value at `path` of `object`. If the resolved value is * `undefined`, the `defaultValue` is returned in its place. * * @static * @memberOf _ * @since 3.7.0 * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path of the property to get. * @param {*} [defaultValue] The value returned for `undefined` resolved values. * @returns {*} Returns the resolved value. * @example * * var object = { 'a': [{ 'b': { 'c': 3 } }] }; * * _.get(object, 'a[0].b.c'); * // => 3 * * _.get(object, ['a', '0', 'b', 'c']); * // => 3 * * _.get(object, 'a.b.c', 'default'); * // => 'default' */ function get(object, path, defaultValue) { var result = object == null ? undefined : baseGet(object, path); return result === undefined ? defaultValue : result; } module.exports = get; /***/ }), /***/ 2307: /***/ (function(module, exports, __webpack_require__) { /* module decorator */ module = __webpack_require__.nmd(module); /** * Lodash (Custom Build) * Build: `lodash modularize exports="npm" -o ./` * Copyright JS Foundation and other contributors * Released under MIT license * Based on Underscore.js 1.8.3 * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors */ /** Used as the size to enable large array optimizations. */ var LARGE_ARRAY_SIZE = 200; /** Used to stand-in for `undefined` hash values. */ var HASH_UNDEFINED = '__lodash_hash_undefined__'; /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG = 1, COMPARE_UNORDERED_FLAG = 2; /** Used as references for various `Number` constants. */ var MAX_SAFE_INTEGER = 9007199254740991; /** `Object#toString` result references. */ var argsTag = '[object Arguments]', arrayTag = '[object Array]', asyncTag = '[object AsyncFunction]', boolTag = '[object Boolean]', dateTag = '[object Date]', errorTag = '[object Error]', funcTag = '[object Function]', genTag = '[object GeneratorFunction]', mapTag = '[object Map]', numberTag = '[object Number]', nullTag = '[object Null]', objectTag = '[object Object]', promiseTag = '[object Promise]', proxyTag = '[object Proxy]', regexpTag = '[object RegExp]', setTag = '[object Set]', stringTag = '[object String]', symbolTag = '[object Symbol]', undefinedTag = '[object Undefined]', weakMapTag = '[object WeakMap]'; var arrayBufferTag = '[object ArrayBuffer]', dataViewTag = '[object DataView]', float32Tag = '[object Float32Array]', float64Tag = '[object Float64Array]', int8Tag = '[object Int8Array]', int16Tag = '[object Int16Array]', int32Tag = '[object Int32Array]', uint8Tag = '[object Uint8Array]', uint8ClampedTag = '[object Uint8ClampedArray]', uint16Tag = '[object Uint16Array]', uint32Tag = '[object Uint32Array]'; /** * Used to match `RegExp` * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). */ var reRegExpChar = /[\\^$.*+?()[\]{}|]/g; /** Used to detect host constructors (Safari). */ var reIsHostCtor = /^\[object .+?Constructor\]$/; /** Used to detect unsigned integer values. */ var reIsUint = /^(?:0|[1-9]\d*)$/; /** Used to identify `toStringTag` values of typed arrays. */ var typedArrayTags = {}; typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = typedArrayTags[uint32Tag] = true; typedArrayTags[argsTag] = typedArrayTags[arrayTag] = typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = typedArrayTags[errorTag] = typedArrayTags[funcTag] = typedArrayTags[mapTag] = typedArrayTags[numberTag] = typedArrayTags[objectTag] = typedArrayTags[regexpTag] = typedArrayTags[setTag] = typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false; /** Detect free variable `global` from Node.js. */ var freeGlobal = typeof __webpack_require__.g == 'object' && __webpack_require__.g && __webpack_require__.g.Object === Object && __webpack_require__.g; /** Detect free variable `self`. */ var freeSelf = typeof self == 'object' && self && self.Object === Object && self; /** Used as a reference to the global object. */ var root = freeGlobal || freeSelf || Function('return this')(); /** Detect free variable `exports`. */ var freeExports = true && exports && !exports.nodeType && exports; /** Detect free variable `module`. */ var freeModule = freeExports && "object" == 'object' && module && !module.nodeType && module; /** Detect the popular CommonJS extension `module.exports`. */ var moduleExports = freeModule && freeModule.exports === freeExports; /** Detect free variable `process` from Node.js. */ var freeProcess = moduleExports && freeGlobal.process; /** Used to access faster Node.js helpers. */ var nodeUtil = (function() { try { return freeProcess && freeProcess.binding && freeProcess.binding('util'); } catch (e) {} }()); /* Node.js helper references. */ var nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray; /** * A specialized version of `_.filter` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {Array} Returns the new filtered array. */ function arrayFilter(array, predicate) { var index = -1, length = array == null ? 0 : array.length, resIndex = 0, result = []; while (++index < length) { var value = array[index]; if (predicate(value, index, array)) { result[resIndex++] = value; } } return result; } /** * Appends the elements of `values` to `array`. * * @private * @param {Array} array The array to modify. * @param {Array} values The values to append. * @returns {Array} Returns `array`. */ function arrayPush(array, values) { var index = -1, length = values.length, offset = array.length; while (++index < length) { array[offset + index] = values[index]; } return array; } /** * A specialized version of `_.some` for arrays without support for iteratee * shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {boolean} Returns `true` if any element passes the predicate check, * else `false`. */ function arraySome(array, predicate) { var index = -1, length = array == null ? 0 : array.length; while (++index < length) { if (predicate(array[index], index, array)) { return true; } } return false; } /** * The base implementation of `_.times` without support for iteratee shorthands * or max array length checks. * * @private * @param {number} n The number of times to invoke `iteratee`. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns the array of results. */ function baseTimes(n, iteratee) { var index = -1, result = Array(n); while (++index < n) { result[index] = iteratee(index); } return result; } /** * The base implementation of `_.unary` without support for storing metadata. * * @private * @param {Function} func The function to cap arguments for. * @returns {Function} Returns the new capped function. */ function baseUnary(func) { return function(value) { return func(value); }; } /** * Checks if a `cache` value for `key` exists. * * @private * @param {Object} cache The cache to query. * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function cacheHas(cache, key) { return cache.has(key); } /** * Gets the value at `key` of `object`. * * @private * @param {Object} [object] The object to query. * @param {string} key The key of the property to get. * @returns {*} Returns the property value. */ function getValue(object, key) { return object == null ? undefined : object[key]; } /** * Converts `map` to its key-value pairs. * * @private * @param {Object} map The map to convert. * @returns {Array} Returns the key-value pairs. */ function mapToArray(map) { var index = -1, result = Array(map.size); map.forEach(function(value, key) { result[++index] = [key, value]; }); return result; } /** * Creates a unary function that invokes `func` with its argument transformed. * * @private * @param {Function} func The function to wrap. * @param {Function} transform The argument transform. * @returns {Function} Returns the new function. */ function overArg(func, transform) { return function(arg) { return func(transform(arg)); }; } /** * Converts `set` to an array of its values. * * @private * @param {Object} set The set to convert. * @returns {Array} Returns the values. */ function setToArray(set) { var index = -1, result = Array(set.size); set.forEach(function(value) { result[++index] = value; }); return result; } /** Used for built-in method references. */ var arrayProto = Array.prototype, funcProto = Function.prototype, objectProto = Object.prototype; /** Used to detect overreaching core-js shims. */ var coreJsData = root['__core-js_shared__']; /** Used to resolve the decompiled source of functions. */ var funcToString = funcProto.toString; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** Used to detect methods masquerading as native. */ var maskSrcKey = (function() { var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ''); return uid ? ('Symbol(src)_1.' + uid) : ''; }()); /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) * of values. */ var nativeObjectToString = objectProto.toString; /** Used to detect if a method is native. */ var reIsNative = RegExp('^' + funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&') .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' ); /** Built-in value references. */ var Buffer = moduleExports ? root.Buffer : undefined, Symbol = root.Symbol, Uint8Array = root.Uint8Array, propertyIsEnumerable = objectProto.propertyIsEnumerable, splice = arrayProto.splice, symToStringTag = Symbol ? Symbol.toStringTag : undefined; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeGetSymbols = Object.getOwnPropertySymbols, nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined, nativeKeys = overArg(Object.keys, Object); /* Built-in method references that are verified to be native. */ var DataView = getNative(root, 'DataView'), Map = getNative(root, 'Map'), Promise = getNative(root, 'Promise'), Set = getNative(root, 'Set'), WeakMap = getNative(root, 'WeakMap'), nativeCreate = getNative(Object, 'create'); /** Used to detect maps, sets, and weakmaps. */ var dataViewCtorString = toSource(DataView), mapCtorString = toSource(Map), promiseCtorString = toSource(Promise), setCtorString = toSource(Set), weakMapCtorString = toSource(WeakMap); /** Used to convert symbols to primitives and strings. */ var symbolProto = Symbol ? Symbol.prototype : undefined, symbolValueOf = symbolProto ? symbolProto.valueOf : undefined; /** * Creates a hash object. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function Hash(entries) { var index = -1, length = entries == null ? 0 : entries.length; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } /** * Removes all key-value entries from the hash. * * @private * @name clear * @memberOf Hash */ function hashClear() { this.__data__ = nativeCreate ? nativeCreate(null) : {}; this.size = 0; } /** * Removes `key` and its value from the hash. * * @private * @name delete * @memberOf Hash * @param {Object} hash The hash to modify. * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function hashDelete(key) { var result = this.has(key) && delete this.__data__[key]; this.size -= result ? 1 : 0; return result; } /** * Gets the hash value for `key`. * * @private * @name get * @memberOf Hash * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function hashGet(key) { var data = this.__data__; if (nativeCreate) { var result = data[key]; return result === HASH_UNDEFINED ? undefined : result; } return hasOwnProperty.call(data, key) ? data[key] : undefined; } /** * Checks if a hash value for `key` exists. * * @private * @name has * @memberOf Hash * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function hashHas(key) { var data = this.__data__; return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key); } /** * Sets the hash `key` to `value`. * * @private * @name set * @memberOf Hash * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the hash instance. */ function hashSet(key, value) { var data = this.__data__; this.size += this.has(key) ? 0 : 1; data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value; return this; } // Add methods to `Hash`. Hash.prototype.clear = hashClear; Hash.prototype['delete'] = hashDelete; Hash.prototype.get = hashGet; Hash.prototype.has = hashHas; Hash.prototype.set = hashSet; /** * Creates an list cache object. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function ListCache(entries) { var index = -1, length = entries == null ? 0 : entries.length; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } /** * Removes all key-value entries from the list cache. * * @private * @name clear * @memberOf ListCache */ function listCacheClear() { this.__data__ = []; this.size = 0; } /** * Removes `key` and its value from the list cache. * * @private * @name delete * @memberOf ListCache * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function listCacheDelete(key) { var data = this.__data__, index = assocIndexOf(data, key); if (index < 0) { return false; } var lastIndex = data.length - 1; if (index == lastIndex) { data.pop(); } else { splice.call(data, index, 1); } --this.size; return true; } /** * Gets the list cache value for `key`. * * @private * @name get * @memberOf ListCache * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function listCacheGet(key) { var data = this.__data__, index = assocIndexOf(data, key); return index < 0 ? undefined : data[index][1]; } /** * Checks if a list cache value for `key` exists. * * @private * @name has * @memberOf ListCache * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function listCacheHas(key) { return assocIndexOf(this.__data__, key) > -1; } /** * Sets the list cache `key` to `value`. * * @private * @name set * @memberOf ListCache * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the list cache instance. */ function listCacheSet(key, value) { var data = this.__data__, index = assocIndexOf(data, key); if (index < 0) { ++this.size; data.push([key, value]); } else { data[index][1] = value; } return this; } // Add methods to `ListCache`. ListCache.prototype.clear = listCacheClear; ListCache.prototype['delete'] = listCacheDelete; ListCache.prototype.get = listCacheGet; ListCache.prototype.has = listCacheHas; ListCache.prototype.set = listCacheSet; /** * Creates a map cache object to store key-value pairs. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function MapCache(entries) { var index = -1, length = entries == null ? 0 : entries.length; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } /** * Removes all key-value entries from the map. * * @private * @name clear * @memberOf MapCache */ function mapCacheClear() { this.size = 0; this.__data__ = { 'hash': new Hash, 'map': new (Map || ListCache), 'string': new Hash }; } /** * Removes `key` and its value from the map. * * @private * @name delete * @memberOf MapCache * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function mapCacheDelete(key) { var result = getMapData(this, key)['delete'](key); this.size -= result ? 1 : 0; return result; } /** * Gets the map value for `key`. * * @private * @name get * @memberOf MapCache * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function mapCacheGet(key) { return getMapData(this, key).get(key); } /** * Checks if a map value for `key` exists. * * @private * @name has * @memberOf MapCache * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function mapCacheHas(key) { return getMapData(this, key).has(key); } /** * Sets the map `key` to `value`. * * @private * @name set * @memberOf MapCache * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the map cache instance. */ function mapCacheSet(key, value) { var data = getMapData(this, key), size = data.size; data.set(key, value); this.size += data.size == size ? 0 : 1; return this; } // Add methods to `MapCache`. MapCache.prototype.clear = mapCacheClear; MapCache.prototype['delete'] = mapCacheDelete; MapCache.prototype.get = mapCacheGet; MapCache.prototype.has = mapCacheHas; MapCache.prototype.set = mapCacheSet; /** * * Creates an array cache object to store unique values. * * @private * @constructor * @param {Array} [values] The values to cache. */ function SetCache(values) { var index = -1, length = values == null ? 0 : values.length; this.__data__ = new MapCache; while (++index < length) { this.add(values[index]); } } /** * Adds `value` to the array cache. * * @private * @name add * @memberOf SetCache * @alias push * @param {*} value The value to cache. * @returns {Object} Returns the cache instance. */ function setCacheAdd(value) { this.__data__.set(value, HASH_UNDEFINED); return this; } /** * Checks if `value` is in the array cache. * * @private * @name has * @memberOf SetCache * @param {*} value The value to search for. * @returns {number} Returns `true` if `value` is found, else `false`. */ function setCacheHas(value) { return this.__data__.has(value); } // Add methods to `SetCache`. SetCache.prototype.add = SetCache.prototype.push = setCacheAdd; SetCache.prototype.has = setCacheHas; /** * Creates a stack cache object to store key-value pairs. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function Stack(entries) { var data = this.__data__ = new ListCache(entries); this.size = data.size; } /** * Removes all key-value entries from the stack. * * @private * @name clear * @memberOf Stack */ function stackClear() { this.__data__ = new ListCache; this.size = 0; } /** * Removes `key` and its value from the stack. * * @private * @name delete * @memberOf Stack * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function stackDelete(key) { var data = this.__data__, result = data['delete'](key); this.size = data.size; return result; } /** * Gets the stack value for `key`. * * @private * @name get * @memberOf Stack * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function stackGet(key) { return this.__data__.get(key); } /** * Checks if a stack value for `key` exists. * * @private * @name has * @memberOf Stack * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function stackHas(key) { return this.__data__.has(key); } /** * Sets the stack `key` to `value`. * * @private * @name set * @memberOf Stack * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the stack cache instance. */ function stackSet(key, value) { var data = this.__data__; if (data instanceof ListCache) { var pairs = data.__data__; if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) { pairs.push([key, value]); this.size = ++data.size; return this; } data = this.__data__ = new MapCache(pairs); } data.set(key, value); this.size = data.size; return this; } // Add methods to `Stack`. Stack.prototype.clear = stackClear; Stack.prototype['delete'] = stackDelete; Stack.prototype.get = stackGet; Stack.prototype.has = stackHas; Stack.prototype.set = stackSet; /** * Creates an array of the enumerable property names of the array-like `value`. * * @private * @param {*} value The value to query. * @param {boolean} inherited Specify returning inherited property names. * @returns {Array} Returns the array of property names. */ function arrayLikeKeys(value, inherited) { var isArr = isArray(value), isArg = !isArr && isArguments(value), isBuff = !isArr && !isArg && isBuffer(value), isType = !isArr && !isArg && !isBuff && isTypedArray(value), skipIndexes = isArr || isArg || isBuff || isType, result = skipIndexes ? baseTimes(value.length, String) : [], length = result.length; for (var key in value) { if ((inherited || hasOwnProperty.call(value, key)) && !(skipIndexes && ( // Safari 9 has enumerable `arguments.length` in strict mode. key == 'length' || // Node.js 0.10 has enumerable non-index properties on buffers. (isBuff && (key == 'offset' || key == 'parent')) || // PhantomJS 2 has enumerable non-index properties on typed arrays. (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) || // Skip index properties. isIndex(key, length) ))) { result.push(key); } } return result; } /** * Gets the index at which the `key` is found in `array` of key-value pairs. * * @private * @param {Array} array The array to inspect. * @param {*} key The key to search for. * @returns {number} Returns the index of the matched value, else `-1`. */ function assocIndexOf(array, key) { var length = array.length; while (length--) { if (eq(array[length][0], key)) { return length; } } return -1; } /** * The base implementation of `getAllKeys` and `getAllKeysIn` which uses * `keysFunc` and `symbolsFunc` to get the enumerable property names and * symbols of `object`. * * @private * @param {Object} object The object to query. * @param {Function} keysFunc The function to get the keys of `object`. * @param {Function} symbolsFunc The function to get the symbols of `object`. * @returns {Array} Returns the array of property names and symbols. */ function baseGetAllKeys(object, keysFunc, symbolsFunc) { var result = keysFunc(object); return isArray(object) ? result : arrayPush(result, symbolsFunc(object)); } /** * The base implementation of `getTag` without fallbacks for buggy environments. * * @private * @param {*} value The value to query. * @returns {string} Returns the `toStringTag`. */ function baseGetTag(value) { if (value == null) { return value === undefined ? undefinedTag : nullTag; } return (symToStringTag && symToStringTag in Object(value)) ? getRawTag(value) : objectToString(value); } /** * The base implementation of `_.isArguments`. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an `arguments` object, */ function baseIsArguments(value) { return isObjectLike(value) && baseGetTag(value) == argsTag; } /** * The base implementation of `_.isEqual` which supports partial comparisons * and tracks traversed objects. * * @private * @param {*} value The value to compare. * @param {*} other The other value to compare. * @param {boolean} bitmask The bitmask flags. * 1 - Unordered comparison * 2 - Partial comparison * @param {Function} [customizer] The function to customize comparisons. * @param {Object} [stack] Tracks traversed `value` and `other` objects. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. */ function baseIsEqual(value, other, bitmask, customizer, stack) { if (value === other) { return true; } if (value == null || other == null || (!isObjectLike(value) && !isObjectLike(other))) { return value !== value && other !== other; } return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack); } /** * A specialized version of `baseIsEqual` for arrays and objects which performs * deep comparisons and tracks traversed objects enabling objects with circular * references to be compared. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} [stack] Tracks traversed `object` and `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) { var objIsArr = isArray(object), othIsArr = isArray(other), objTag = objIsArr ? arrayTag : getTag(object), othTag = othIsArr ? arrayTag : getTag(other); objTag = objTag == argsTag ? objectTag : objTag; othTag = othTag == argsTag ? objectTag : othTag; var objIsObj = objTag == objectTag, othIsObj = othTag == objectTag, isSameTag = objTag == othTag; if (isSameTag && isBuffer(object)) { if (!isBuffer(other)) { return false; } objIsArr = true; objIsObj = false; } if (isSameTag && !objIsObj) { stack || (stack = new Stack); return (objIsArr || isTypedArray(object)) ? equalArrays(object, other, bitmask, customizer, equalFunc, stack) : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack); } if (!(bitmask & COMPARE_PARTIAL_FLAG)) { var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'), othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__'); if (objIsWrapped || othIsWrapped) { var objUnwrapped = objIsWrapped ? object.value() : object, othUnwrapped = othIsWrapped ? other.value() : other; stack || (stack = new Stack); return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack); } } if (!isSameTag) { return false; } stack || (stack = new Stack); return equalObjects(object, other, bitmask, customizer, equalFunc, stack); } /** * The base implementation of `_.isNative` without bad shim checks. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a native function, * else `false`. */ function baseIsNative(value) { if (!isObject(value) || isMasked(value)) { return false; } var pattern = isFunction(value) ? reIsNative : reIsHostCtor; return pattern.test(toSource(value)); } /** * The base implementation of `_.isTypedArray` without Node.js optimizations. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. */ function baseIsTypedArray(value) { return isObjectLike(value) && isLength(value.length) && !!typedArrayTags[baseGetTag(value)]; } /** * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. */ function baseKeys(object) { if (!isPrototype(object)) { return nativeKeys(object); } var result = []; for (var key in Object(object)) { if (hasOwnProperty.call(object, key) && key != 'constructor') { result.push(key); } } return result; } /** * A specialized version of `baseIsEqualDeep` for arrays with support for * partial deep comparisons. * * @private * @param {Array} array The array to compare. * @param {Array} other The other array to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} stack Tracks traversed `array` and `other` objects. * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`. */ function equalArrays(array, other, bitmask, customizer, equalFunc, stack) { var isPartial = bitmask & COMPARE_PARTIAL_FLAG, arrLength = array.length, othLength = other.length; if (arrLength != othLength && !(isPartial && othLength > arrLength)) { return false; } // Assume cyclic values are equal. var stacked = stack.get(array); if (stacked && stack.get(other)) { return stacked == other; } var index = -1, result = true, seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new SetCache : undefined; stack.set(array, other); stack.set(other, array); // Ignore non-index properties. while (++index < arrLength) { var arrValue = array[index], othValue = other[index]; if (customizer) { var compared = isPartial ? customizer(othValue, arrValue, index, other, array, stack) : customizer(arrValue, othValue, index, array, other, stack); } if (compared !== undefined) { if (compared) { continue; } result = false; break; } // Recursively compare arrays (susceptible to call stack limits). if (seen) { if (!arraySome(other, function(othValue, othIndex) { if (!cacheHas(seen, othIndex) && (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) { return seen.push(othIndex); } })) { result = false; break; } } else if (!( arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack) )) { result = false; break; } } stack['delete'](array); stack['delete'](other); return result; } /** * A specialized version of `baseIsEqualDeep` for comparing objects of * the same `toStringTag`. * * **Note:** This function only supports comparing values with tags of * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {string} tag The `toStringTag` of the objects to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} stack Tracks traversed `object` and `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) { switch (tag) { case dataViewTag: if ((object.byteLength != other.byteLength) || (object.byteOffset != other.byteOffset)) { return false; } object = object.buffer; other = other.buffer; case arrayBufferTag: if ((object.byteLength != other.byteLength) || !equalFunc(new Uint8Array(object), new Uint8Array(other))) { return false; } return true; case boolTag: case dateTag: case numberTag: // Coerce booleans to `1` or `0` and dates to milliseconds. // Invalid dates are coerced to `NaN`. return eq(+object, +other); case errorTag: return object.name == other.name && object.message == other.message; case regexpTag: case stringTag: // Coerce regexes to strings and treat strings, primitives and objects, // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring // for more details. return object == (other + ''); case mapTag: var convert = mapToArray; case setTag: var isPartial = bitmask & COMPARE_PARTIAL_FLAG; convert || (convert = setToArray); if (object.size != other.size && !isPartial) { return false; } // Assume cyclic values are equal. var stacked = stack.get(object); if (stacked) { return stacked == other; } bitmask |= COMPARE_UNORDERED_FLAG; // Recursively compare objects (susceptible to call stack limits). stack.set(object, other); var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack); stack['delete'](object); return result; case symbolTag: if (symbolValueOf) { return symbolValueOf.call(object) == symbolValueOf.call(other); } } return false; } /** * A specialized version of `baseIsEqualDeep` for objects with support for * partial deep comparisons. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} stack Tracks traversed `object` and `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function equalObjects(object, other, bitmask, customizer, equalFunc, stack) { var isPartial = bitmask & COMPARE_PARTIAL_FLAG, objProps = getAllKeys(object), objLength = objProps.length, othProps = getAllKeys(other), othLength = othProps.length; if (objLength != othLength && !isPartial) { return false; } var index = objLength; while (index--) { var key = objProps[index]; if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) { return false; } } // Assume cyclic values are equal. var stacked = stack.get(object); if (stacked && stack.get(other)) { return stacked == other; } var result = true; stack.set(object, other); stack.set(other, object); var skipCtor = isPartial; while (++index < objLength) { key = objProps[index]; var objValue = object[key], othValue = other[key]; if (customizer) { var compared = isPartial ? customizer(othValue, objValue, key, other, object, stack) : customizer(objValue, othValue, key, object, other, stack); } // Recursively compare objects (susceptible to call stack limits). if (!(compared === undefined ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack)) : compared )) { result = false; break; } skipCtor || (skipCtor = key == 'constructor'); } if (result && !skipCtor) { var objCtor = object.constructor, othCtor = other.constructor; // Non `Object` object instances with different constructors are not equal. if (objCtor != othCtor && ('constructor' in object && 'constructor' in other) && !(typeof objCtor == 'function' && objCtor instanceof objCtor && typeof othCtor == 'function' && othCtor instanceof othCtor)) { result = false; } } stack['delete'](object); stack['delete'](other); return result; } /** * Creates an array of own enumerable property names and symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names and symbols. */ function getAllKeys(object) { return baseGetAllKeys(object, keys, getSymbols); } /** * Gets the data for `map`. * * @private * @param {Object} map The map to query. * @param {string} key The reference key. * @returns {*} Returns the map data. */ function getMapData(map, key) { var data = map.__data__; return isKeyable(key) ? data[typeof key == 'string' ? 'string' : 'hash'] : data.map; } /** * Gets the native function at `key` of `object`. * * @private * @param {Object} object The object to query. * @param {string} key The key of the method to get. * @returns {*} Returns the function if it's native, else `undefined`. */ function getNative(object, key) { var value = getValue(object, key); return baseIsNative(value) ? value : undefined; } /** * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values. * * @private * @param {*} value The value to query. * @returns {string} Returns the raw `toStringTag`. */ function getRawTag(value) { var isOwn = hasOwnProperty.call(value, symToStringTag), tag = value[symToStringTag]; try { value[symToStringTag] = undefined; var unmasked = true; } catch (e) {} var result = nativeObjectToString.call(value); if (unmasked) { if (isOwn) { value[symToStringTag] = tag; } else { delete value[symToStringTag]; } } return result; } /** * Creates an array of the own enumerable symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of symbols. */ var getSymbols = !nativeGetSymbols ? stubArray : function(object) { if (object == null) { return []; } object = Object(object); return arrayFilter(nativeGetSymbols(object), function(symbol) { return propertyIsEnumerable.call(object, symbol); }); }; /** * Gets the `toStringTag` of `value`. * * @private * @param {*} value The value to query. * @returns {string} Returns the `toStringTag`. */ var getTag = baseGetTag; // Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6. if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) || (Map && getTag(new Map) != mapTag) || (Promise && getTag(Promise.resolve()) != promiseTag) || (Set && getTag(new Set) != setTag) || (WeakMap && getTag(new WeakMap) != weakMapTag)) { getTag = function(value) { var result = baseGetTag(value), Ctor = result == objectTag ? value.constructor : undefined, ctorString = Ctor ? toSource(Ctor) : ''; if (ctorString) { switch (ctorString) { case dataViewCtorString: return dataViewTag; case mapCtorString: return mapTag; case promiseCtorString: return promiseTag; case setCtorString: return setTag; case weakMapCtorString: return weakMapTag; } } return result; }; } /** * Checks if `value` is a valid array-like index. * * @private * @param {*} value The value to check. * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. */ function isIndex(value, length) { length = length == null ? MAX_SAFE_INTEGER : length; return !!length && (typeof value == 'number' || reIsUint.test(value)) && (value > -1 && value % 1 == 0 && value < length); } /** * Checks if `value` is suitable for use as unique object key. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is suitable, else `false`. */ function isKeyable(value) { var type = typeof value; return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean') ? (value !== '__proto__') : (value === null); } /** * Checks if `func` has its source masked. * * @private * @param {Function} func The function to check. * @returns {boolean} Returns `true` if `func` is masked, else `false`. */ function isMasked(func) { return !!maskSrcKey && (maskSrcKey in func); } /** * Checks if `value` is likely a prototype object. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. */ function isPrototype(value) { var Ctor = value && value.constructor, proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto; return value === proto; } /** * Converts `value` to a string using `Object.prototype.toString`. * * @private * @param {*} value The value to convert. * @returns {string} Returns the converted string. */ function objectToString(value) { return nativeObjectToString.call(value); } /** * Converts `func` to its source code. * * @private * @param {Function} func The function to convert. * @returns {string} Returns the source code. */ function toSource(func) { if (func != null) { try { return funcToString.call(func); } catch (e) {} try { return (func + ''); } catch (e) {} } return ''; } /** * Performs a * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * comparison between two values to determine if they are equivalent. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. * @example * * var object = { 'a': 1 }; * var other = { 'a': 1 }; * * _.eq(object, object); * // => true * * _.eq(object, other); * // => false * * _.eq('a', 'a'); * // => true * * _.eq('a', Object('a')); * // => false * * _.eq(NaN, NaN); * // => true */ function eq(value, other) { return value === other || (value !== value && other !== other); } /** * Checks if `value` is likely an `arguments` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an `arguments` object, * else `false`. * @example * * _.isArguments(function() { return arguments; }()); * // => true * * _.isArguments([1, 2, 3]); * // => false */ var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) { return isObjectLike(value) && hasOwnProperty.call(value, 'callee') && !propertyIsEnumerable.call(value, 'callee'); }; /** * Checks if `value` is classified as an `Array` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an array, else `false`. * @example * * _.isArray([1, 2, 3]); * // => true * * _.isArray(document.body.children); * // => false * * _.isArray('abc'); * // => false * * _.isArray(_.noop); * // => false */ var isArray = Array.isArray; /** * Checks if `value` is array-like. A value is considered array-like if it's * not a function and has a `value.length` that's an integer greater than or * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is array-like, else `false`. * @example * * _.isArrayLike([1, 2, 3]); * // => true * * _.isArrayLike(document.body.children); * // => true * * _.isArrayLike('abc'); * // => true * * _.isArrayLike(_.noop); * // => false */ function isArrayLike(value) { return value != null && isLength(value.length) && !isFunction(value); } /** * Checks if `value` is a buffer. * * @static * @memberOf _ * @since 4.3.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a buffer, else `false`. * @example * * _.isBuffer(new Buffer(2)); * // => true * * _.isBuffer(new Uint8Array(2)); * // => false */ var isBuffer = nativeIsBuffer || stubFalse; /** * Performs a deep comparison between two values to determine if they are * equivalent. * * **Note:** This method supports comparing arrays, array buffers, booleans, * date objects, error objects, maps, numbers, `Object` objects, regexes, * sets, strings, symbols, and typed arrays. `Object` objects are compared * by their own, not inherited, enumerable properties. Functions and DOM * nodes are compared by strict equality, i.e. `===`. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. * @example * * var object = { 'a': 1 }; * var other = { 'a': 1 }; * * _.isEqual(object, other); * // => true * * object === other; * // => false */ function isEqual(value, other) { return baseIsEqual(value, other); } /** * Checks if `value` is classified as a `Function` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a function, else `false`. * @example * * _.isFunction(_); * // => true * * _.isFunction(/abc/); * // => false */ function isFunction(value) { if (!isObject(value)) { return false; } // The use of `Object#toString` avoids issues with the `typeof` operator // in Safari 9 which returns 'object' for typed arrays and other constructors. var tag = baseGetTag(value); return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag; } /** * Checks if `value` is a valid array-like length. * * **Note:** This method is loosely based on * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. * @example * * _.isLength(3); * // => true * * _.isLength(Number.MIN_VALUE); * // => false * * _.isLength(Infinity); * // => false * * _.isLength('3'); * // => false */ function isLength(value) { return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; } /** * Checks if `value` is the * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an object, else `false`. * @example * * _.isObject({}); * // => true * * _.isObject([1, 2, 3]); * // => true * * _.isObject(_.noop); * // => true * * _.isObject(null); * // => false */ function isObject(value) { var type = typeof value; return value != null && (type == 'object' || type == 'function'); } /** * Checks if `value` is object-like. A value is object-like if it's not `null` * and has a `typeof` result of "object". * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is object-like, else `false`. * @example * * _.isObjectLike({}); * // => true * * _.isObjectLike([1, 2, 3]); * // => true * * _.isObjectLike(_.noop); * // => false * * _.isObjectLike(null); * // => false */ function isObjectLike(value) { return value != null && typeof value == 'object'; } /** * Checks if `value` is classified as a typed array. * * @static * @memberOf _ * @since 3.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. * @example * * _.isTypedArray(new Uint8Array); * // => true * * _.isTypedArray([]); * // => false */ var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray; /** * Creates an array of the own enumerable property names of `object`. * * **Note:** Non-object values are coerced to objects. See the * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) * for more details. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.keys(new Foo); * // => ['a', 'b'] (iteration order is not guaranteed) * * _.keys('hi'); * // => ['0', '1'] */ function keys(object) { return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object); } /** * This method returns a new empty array. * * @static * @memberOf _ * @since 4.13.0 * @category Util * @returns {Array} Returns the new empty array. * @example * * var arrays = _.times(2, _.stubArray); * * console.log(arrays); * // => [[], []] * * console.log(arrays[0] === arrays[1]); * // => false */ function stubArray() { return []; } /** * This method returns `false`. * * @static * @memberOf _ * @since 4.13.0 * @category Util * @returns {boolean} Returns `false`. * @example * * _.times(2, _.stubFalse); * // => [false, false] */ function stubFalse() { return false; } module.exports = isEqual; /***/ }), /***/ 4461: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { /** * lodash (Custom Build) * Build: `lodash modularize exports="npm" -o ./` * Copyright jQuery Foundation and other contributors * Released under MIT license * Based on Underscore.js 1.8.3 * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors */ /** Used as references for various `Number` constants. */ var INFINITY = 1 / 0; /** `Object#toString` result references. */ var symbolTag = '[object Symbol]'; /** Detect free variable `global` from Node.js. */ var freeGlobal = typeof __webpack_require__.g == 'object' && __webpack_require__.g && __webpack_require__.g.Object === Object && __webpack_require__.g; /** Detect free variable `self`. */ var freeSelf = typeof self == 'object' && self && self.Object === Object && self; /** Used as a reference to the global object. */ var root = freeGlobal || freeSelf || Function('return this')(); /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to generate unique IDs. */ var idCounter = 0; /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) * of values. */ var objectToString = objectProto.toString; /** Built-in value references. */ var Symbol = root.Symbol; /** Used to convert symbols to primitives and strings. */ var symbolProto = Symbol ? Symbol.prototype : undefined, symbolToString = symbolProto ? symbolProto.toString : undefined; /** * The base implementation of `_.toString` which doesn't convert nullish * values to empty strings. * * @private * @param {*} value The value to process. * @returns {string} Returns the string. */ function baseToString(value) { // Exit early for strings to avoid a performance hit in some environments. if (typeof value == 'string') { return value; } if (isSymbol(value)) { return symbolToString ? symbolToString.call(value) : ''; } var result = (value + ''); return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; } /** * Checks if `value` is object-like. A value is object-like if it's not `null` * and has a `typeof` result of "object". * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is object-like, else `false`. * @example * * _.isObjectLike({}); * // => true * * _.isObjectLike([1, 2, 3]); * // => true * * _.isObjectLike(_.noop); * // => false * * _.isObjectLike(null); * // => false */ function isObjectLike(value) { return !!value && typeof value == 'object'; } /** * Checks if `value` is classified as a `Symbol` primitive or object. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. * @example * * _.isSymbol(Symbol.iterator); * // => true * * _.isSymbol('abc'); * // => false */ function isSymbol(value) { return typeof value == 'symbol' || (isObjectLike(value) && objectToString.call(value) == symbolTag); } /** * Converts `value` to a string. An empty string is returned for `null` * and `undefined` values. The sign of `-0` is preserved. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to process. * @returns {string} Returns the string. * @example * * _.toString(null); * // => '' * * _.toString(-0); * // => '-0' * * _.toString([1, 2, 3]); * // => '1,2,3' */ function toString(value) { return value == null ? '' : baseToString(value); } /** * Generates a unique ID. If `prefix` is given, the ID is appended to it. * * @static * @since 0.1.0 * @memberOf _ * @category Util * @param {string} [prefix=''] The value to prefix the ID with. * @returns {string} Returns the unique ID. * @example * * _.uniqueId('contact_'); * // => 'contact_104' * * _.uniqueId(); * // => '105' */ function uniqueId(prefix) { var id = ++idCounter; return toString(prefix) + id; } module.exports = uniqueId; /***/ }), /***/ 39: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { /** * lodash (Custom Build) * Build: `lodash modularize exports="npm" -o ./` * Copyright jQuery Foundation and other contributors * Released under MIT license * Based on Underscore.js 1.8.3 * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors */ /** Used as references for various `Number` constants. */ var INFINITY = 1 / 0; /** `Object#toString` result references. */ var symbolTag = '[object Symbol]'; /** Used to compose unicode character classes. */ var rsAstralRange = '\\ud800-\\udfff', rsComboMarksRange = '\\u0300-\\u036f\\ufe20-\\ufe23', rsComboSymbolsRange = '\\u20d0-\\u20f0', rsVarRange = '\\ufe0e\\ufe0f'; /** Used to compose unicode capture groups. */ var rsAstral = '[' + rsAstralRange + ']', rsCombo = '[' + rsComboMarksRange + rsComboSymbolsRange + ']', rsFitz = '\\ud83c[\\udffb-\\udfff]', rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')', rsNonAstral = '[^' + rsAstralRange + ']', rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}', rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]', rsZWJ = '\\u200d'; /** Used to compose unicode regexes. */ var reOptMod = rsModifier + '?', rsOptVar = '[' + rsVarRange + ']?', rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*', rsSeq = rsOptVar + reOptMod + rsOptJoin, rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')'; /** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */ var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g'); /** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */ var reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboMarksRange + rsComboSymbolsRange + rsVarRange + ']'); /** Detect free variable `global` from Node.js. */ var freeGlobal = typeof __webpack_require__.g == 'object' && __webpack_require__.g && __webpack_require__.g.Object === Object && __webpack_require__.g; /** Detect free variable `self`. */ var freeSelf = typeof self == 'object' && self && self.Object === Object && self; /** Used as a reference to the global object. */ var root = freeGlobal || freeSelf || Function('return this')(); /** * Converts an ASCII `string` to an array. * * @private * @param {string} string The string to convert. * @returns {Array} Returns the converted array. */ function asciiToArray(string) { return string.split(''); } /** * Checks if `string` contains Unicode symbols. * * @private * @param {string} string The string to inspect. * @returns {boolean} Returns `true` if a symbol is found, else `false`. */ function hasUnicode(string) { return reHasUnicode.test(string); } /** * Converts `string` to an array. * * @private * @param {string} string The string to convert. * @returns {Array} Returns the converted array. */ function stringToArray(string) { return hasUnicode(string) ? unicodeToArray(string) : asciiToArray(string); } /** * Converts a Unicode `string` to an array. * * @private * @param {string} string The string to convert. * @returns {Array} Returns the converted array. */ function unicodeToArray(string) { return string.match(reUnicode) || []; } /** Used for built-in method references. */ var objectProto = Object.prototype; /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) * of values. */ var objectToString = objectProto.toString; /** Built-in value references. */ var Symbol = root.Symbol; /** Used to convert symbols to primitives and strings. */ var symbolProto = Symbol ? Symbol.prototype : undefined, symbolToString = symbolProto ? symbolProto.toString : undefined; /** * The base implementation of `_.slice` without an iteratee call guard. * * @private * @param {Array} array The array to slice. * @param {number} [start=0] The start position. * @param {number} [end=array.length] The end position. * @returns {Array} Returns the slice of `array`. */ function baseSlice(array, start, end) { var index = -1, length = array.length; if (start < 0) { start = -start > length ? 0 : (length + start); } end = end > length ? length : end; if (end < 0) { end += length; } length = start > end ? 0 : ((end - start) >>> 0); start >>>= 0; var result = Array(length); while (++index < length) { result[index] = array[index + start]; } return result; } /** * The base implementation of `_.toString` which doesn't convert nullish * values to empty strings. * * @private * @param {*} value The value to process. * @returns {string} Returns the string. */ function baseToString(value) { // Exit early for strings to avoid a performance hit in some environments. if (typeof value == 'string') { return value; } if (isSymbol(value)) { return symbolToString ? symbolToString.call(value) : ''; } var result = (value + ''); return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; } /** * Casts `array` to a slice if it's needed. * * @private * @param {Array} array The array to inspect. * @param {number} start The start position. * @param {number} [end=array.length] The end position. * @returns {Array} Returns the cast slice. */ function castSlice(array, start, end) { var length = array.length; end = end === undefined ? length : end; return (!start && end >= length) ? array : baseSlice(array, start, end); } /** * Creates a function like `_.lowerFirst`. * * @private * @param {string} methodName The name of the `String` case method to use. * @returns {Function} Returns the new case function. */ function createCaseFirst(methodName) { return function(string) { string = toString(string); var strSymbols = hasUnicode(string) ? stringToArray(string) : undefined; var chr = strSymbols ? strSymbols[0] : string.charAt(0); var trailing = strSymbols ? castSlice(strSymbols, 1).join('') : string.slice(1); return chr[methodName]() + trailing; }; } /** * Checks if `value` is object-like. A value is object-like if it's not `null` * and has a `typeof` result of "object". * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is object-like, else `false`. * @example * * _.isObjectLike({}); * // => true * * _.isObjectLike([1, 2, 3]); * // => true * * _.isObjectLike(_.noop); * // => false * * _.isObjectLike(null); * // => false */ function isObjectLike(value) { return !!value && typeof value == 'object'; } /** * Checks if `value` is classified as a `Symbol` primitive or object. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. * @example * * _.isSymbol(Symbol.iterator); * // => true * * _.isSymbol('abc'); * // => false */ function isSymbol(value) { return typeof value == 'symbol' || (isObjectLike(value) && objectToString.call(value) == symbolTag); } /** * Converts `value` to a string. An empty string is returned for `null` * and `undefined` values. The sign of `-0` is preserved. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to process. * @returns {string} Returns the string. * @example * * _.toString(null); * // => '' * * _.toString(-0); * // => '-0' * * _.toString([1, 2, 3]); * // => '1,2,3' */ function toString(value) { return value == null ? '' : baseToString(value); } /** * Converts the first character of `string` to upper case. * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the converted string. * @example * * _.upperFirst('fred'); * // => 'Fred' * * _.upperFirst('FRED'); * // => 'FRED' */ var upperFirst = createCaseFirst('toUpperCase'); module.exports = upperFirst; /***/ }), /***/ 9626: /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); // extracted by mini-css-extract-plugin /* harmony default export */ __webpack_exports__["default"] = ({}); /***/ }), /***/ 2547: /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); // extracted by mini-css-extract-plugin /* harmony default export */ __webpack_exports__["default"] = ({}); /***/ }), /***/ 5251: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; /** @license React v16.14.0 * react-jsx-runtime.production.min.js * * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var f=__webpack_require__(3899),g=60103;exports.Fragment=60107;if("function"===typeof Symbol&&Symbol.for){var h=Symbol.for;g=h("react.element");exports.Fragment=h("react.fragment")}var m=f.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,n=Object.prototype.hasOwnProperty,p={key:!0,ref:!0,__self:!0,__source:!0}; function q(c,a,k){var b,d={},e=null,l=null;void 0!==k&&(e=""+k);void 0!==a.key&&(e=""+a.key);void 0!==a.ref&&(l=a.ref);for(b in a)n.call(a,b)&&!p.hasOwnProperty(b)&&(d[b]=a[b]);if(c&&c.defaultProps)for(b in a=c.defaultProps,a)void 0===d[b]&&(d[b]=a[b]);return{$$typeof:g,type:c,key:e,ref:l,props:d,_owner:m.current}}exports.jsx=q;exports.jsxs=q; /***/ }), /***/ 5893: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; if (true) { module.exports = __webpack_require__(5251); } else {} /***/ }), /***/ 8808: /***/ (function(__unused_webpack_module, exports) { "use strict"; exports.__esModule = true; exports["default"] = void 0; var compose = function compose() { for (var _len = arguments.length, funcs = new Array(_len), _key = 0; _key < _len; _key++) { funcs[_key] = arguments[_key]; } return funcs.reduce(function (a, b) { return function () { return a(b.apply(void 0, arguments)); }; }, function (arg) { return arg; }); }; var _default = compose; exports["default"] = _default; /***/ }), /***/ 1566: /***/ (function(__unused_webpack_module, exports) { "use strict"; exports.__esModule = true; exports["default"] = void 0; var getDisplayName = function getDisplayName(Component) { if (typeof Component === 'string') { return Component; } if (!Component) { return undefined; } return Component.displayName || Component.name || 'Component'; }; var _default = getDisplayName; exports["default"] = _default; /***/ }), /***/ 6626: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var _interopRequireDefault = __webpack_require__(4836); exports.__esModule = true; exports["default"] = void 0; var _getDisplayName = _interopRequireDefault(__webpack_require__(1566)); var wrapDisplayName = function wrapDisplayName(BaseComponent, hocName) { return hocName + "(" + (0, _getDisplayName.default)(BaseComponent) + ")"; }; var _default = wrapDisplayName; exports["default"] = _default; /***/ }), /***/ 6099: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { ;(function (sax) { // wrapper for non-node envs sax.parser = function (strict, opt) { return new SAXParser(strict, opt) } sax.SAXParser = SAXParser sax.SAXStream = SAXStream sax.createStream = createStream // When we pass the MAX_BUFFER_LENGTH position, start checking for buffer overruns. // When we check, schedule the next check for MAX_BUFFER_LENGTH - (max(buffer lengths)), // since that's the earliest that a buffer overrun could occur. This way, checks are // as rare as required, but as often as necessary to ensure never crossing this bound. // Furthermore, buffers are only tested at most once per write(), so passing a very // large string into write() might have undesirable effects, but this is manageable by // the caller, so it is assumed to be safe. Thus, a call to write() may, in the extreme // edge case, result in creating at most one complete copy of the string passed in. // Set to Infinity to have unlimited buffers. sax.MAX_BUFFER_LENGTH = 64 * 1024 var buffers = [ 'comment', 'sgmlDecl', 'textNode', 'tagName', 'doctype', 'procInstName', 'procInstBody', 'entity', 'attribName', 'attribValue', 'cdata', 'script' ] sax.EVENTS = [ 'text', 'processinginstruction', 'sgmldeclaration', 'doctype', 'comment', 'opentagstart', 'attribute', 'opentag', 'closetag', 'opencdata', 'cdata', 'closecdata', 'error', 'end', 'ready', 'script', 'opennamespace', 'closenamespace' ] function SAXParser (strict, opt) { if (!(this instanceof SAXParser)) { return new SAXParser(strict, opt) } var parser = this clearBuffers(parser) parser.q = parser.c = '' parser.bufferCheckPosition = sax.MAX_BUFFER_LENGTH parser.opt = opt || {} parser.opt.lowercase = parser.opt.lowercase || parser.opt.lowercasetags parser.looseCase = parser.opt.lowercase ? 'toLowerCase' : 'toUpperCase' parser.tags = [] parser.closed = parser.closedRoot = parser.sawRoot = false parser.tag = parser.error = null parser.strict = !!strict parser.noscript = !!(strict || parser.opt.noscript) parser.state = S.BEGIN parser.strictEntities = parser.opt.strictEntities parser.ENTITIES = parser.strictEntities ? Object.create(sax.XML_ENTITIES) : Object.create(sax.ENTITIES) parser.attribList = [] // namespaces form a prototype chain. // it always points at the current tag, // which protos to its parent tag. if (parser.opt.xmlns) { parser.ns = Object.create(rootNS) } // mostly just for error reporting parser.trackPosition = parser.opt.position !== false if (parser.trackPosition) { parser.position = parser.line = parser.column = 0 } emit(parser, 'onready') } if (!Object.create) { Object.create = function (o) { function F () {} F.prototype = o var newf = new F() return newf } } if (!Object.keys) { Object.keys = function (o) { var a = [] for (var i in o) if (o.hasOwnProperty(i)) a.push(i) return a } } function checkBufferLength (parser) { var maxAllowed = Math.max(sax.MAX_BUFFER_LENGTH, 10) var maxActual = 0 for (var i = 0, l = buffers.length; i < l; i++) { var len = parser[buffers[i]].length if (len > maxAllowed) { // Text/cdata nodes can get big, and since they're buffered, // we can get here under normal conditions. // Avoid issues by emitting the text node now, // so at least it won't get any bigger. switch (buffers[i]) { case 'textNode': closeText(parser) break case 'cdata': emitNode(parser, 'oncdata', parser.cdata) parser.cdata = '' break case 'script': emitNode(parser, 'onscript', parser.script) parser.script = '' break default: error(parser, 'Max buffer length exceeded: ' + buffers[i]) } } maxActual = Math.max(maxActual, len) } // schedule the next check for the earliest possible buffer overrun. var m = sax.MAX_BUFFER_LENGTH - maxActual parser.bufferCheckPosition = m + parser.position } function clearBuffers (parser) { for (var i = 0, l = buffers.length; i < l; i++) { parser[buffers[i]] = '' } } function flushBuffers (parser) { closeText(parser) if (parser.cdata !== '') { emitNode(parser, 'oncdata', parser.cdata) parser.cdata = '' } if (parser.script !== '') { emitNode(parser, 'onscript', parser.script) parser.script = '' } } SAXParser.prototype = { end: function () { end(this) }, write: write, resume: function () { this.error = null; return this }, close: function () { return this.write(null) }, flush: function () { flushBuffers(this) } } var Stream try { Stream = (__webpack_require__(2830).Stream) } catch (ex) { Stream = function () {} } var streamWraps = sax.EVENTS.filter(function (ev) { return ev !== 'error' && ev !== 'end' }) function createStream (strict, opt) { return new SAXStream(strict, opt) } function SAXStream (strict, opt) { if (!(this instanceof SAXStream)) { return new SAXStream(strict, opt) } Stream.apply(this) this._parser = new SAXParser(strict, opt) this.writable = true this.readable = true var me = this this._parser.onend = function () { me.emit('end') } this._parser.onerror = function (er) { me.emit('error', er) // if didn't throw, then means error was handled. // go ahead and clear error, so we can write again. me._parser.error = null } this._decoder = null streamWraps.forEach(function (ev) { Object.defineProperty(me, 'on' + ev, { get: function () { return me._parser['on' + ev] }, set: function (h) { if (!h) { me.removeAllListeners(ev) me._parser['on' + ev] = h return h } me.on(ev, h) }, enumerable: true, configurable: false }) }) } SAXStream.prototype = Object.create(Stream.prototype, { constructor: { value: SAXStream } }) SAXStream.prototype.write = function (data) { if (typeof Buffer === 'function' && typeof Buffer.isBuffer === 'function' && Buffer.isBuffer(data)) { if (!this._decoder) { var SD = (__webpack_require__(2553)/* .StringDecoder */ .s) this._decoder = new SD('utf8') } data = this._decoder.write(data) } this._parser.write(data.toString()) this.emit('data', data) return true } SAXStream.prototype.end = function (chunk) { if (chunk && chunk.length) { this.write(chunk) } this._parser.end() return true } SAXStream.prototype.on = function (ev, handler) { var me = this if (!me._parser['on' + ev] && streamWraps.indexOf(ev) !== -1) { me._parser['on' + ev] = function () { var args = arguments.length === 1 ? [arguments[0]] : Array.apply(null, arguments) args.splice(0, 0, ev) me.emit.apply(me, args) } } return Stream.prototype.on.call(me, ev, handler) } // this really needs to be replaced with character classes. // XML allows all manner of ridiculous numbers and digits. var CDATA = '[CDATA[' var DOCTYPE = 'DOCTYPE' var XML_NAMESPACE = 'http://www.w3.org/XML/1998/namespace' var XMLNS_NAMESPACE = 'http://www.w3.org/2000/xmlns/' var rootNS = { xml: XML_NAMESPACE, xmlns: XMLNS_NAMESPACE } // http://www.w3.org/TR/REC-xml/#NT-NameStartChar // This implementation works on strings, a single character at a time // as such, it cannot ever support astral-plane characters (10000-EFFFF) // without a significant breaking change to either this parser, or the // JavaScript language. Implementation of an emoji-capable xml parser // is left as an exercise for the reader. var nameStart = /[:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/ var nameBody = /[:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u00B7\u0300-\u036F\u203F-\u2040.\d-]/ var entityStart = /[#:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/ var entityBody = /[#:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u00B7\u0300-\u036F\u203F-\u2040.\d-]/ function isWhitespace (c) { return c === ' ' || c === '\n' || c === '\r' || c === '\t' } function isQuote (c) { return c === '"' || c === '\'' } function isAttribEnd (c) { return c === '>' || isWhitespace(c) } function isMatch (regex, c) { return regex.test(c) } function notMatch (regex, c) { return !isMatch(regex, c) } var S = 0 sax.STATE = { BEGIN: S++, // leading byte order mark or whitespace BEGIN_WHITESPACE: S++, // leading whitespace TEXT: S++, // general stuff TEXT_ENTITY: S++, // & and such. OPEN_WAKA: S++, // < SGML_DECL: S++, // SCRIPT: S++, //