@loaders.gl/shapefile 4.0.0-alpha.22 → 4.0.0-alpha.24

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,240 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.replaceExtension = exports.loadShapefileSidecarFiles = exports.parseShapefile = exports.parseShapefileInBatches = void 0;
4
- // import type {Feature} from '@loaders.gl/gis';
5
- const loader_utils_1 = require("@loaders.gl/loader-utils");
6
- const gis_1 = require("@loaders.gl/gis");
7
- const proj4_1 = require("@math.gl/proj4");
8
- const parse_shx_1 = require("./parse-shx");
9
- const zip_batch_iterators_1 = require("../streaming/zip-batch-iterators");
10
- const shp_loader_1 = require("../../shp-loader");
11
- const dbf_loader_1 = require("../../dbf-loader");
12
- /**
13
- * Parsing of file in batches
14
- */
15
- // eslint-disable-next-line max-statements, complexity
16
- async function* parseShapefileInBatches(asyncIterator, options, context) {
17
- const { reproject = false, _targetCrs = 'WGS84' } = options?.gis || {};
18
- const { shx, cpg, prj } = await loadShapefileSidecarFiles(options, context);
19
- // parse geometries
20
- const shapeIterable = await (0, loader_utils_1.parseInBatchesFromContext)(asyncIterator, shp_loader_1.SHPLoader, options, context);
21
- // parse properties
22
- let propertyIterable;
23
- const dbfResponse = await context?.fetch(replaceExtension(context?.url || '', 'dbf'));
24
- if (dbfResponse?.ok) {
25
- propertyIterable = await (0, loader_utils_1.parseInBatchesFromContext)(dbfResponse, dbf_loader_1.DBFLoader, {
26
- ...options,
27
- dbf: { encoding: cpg || 'latin1' }
28
- }, context);
29
- }
30
- // When `options.metadata` is `true`, there's an extra initial `metadata`
31
- // object before the iterator starts. zipBatchIterators expects to receive
32
- // batches of Array objects, and will fail with non-iterable batches, so it's
33
- // important to skip over the first batch.
34
- let shapeHeader = (await shapeIterable.next()).value;
35
- if (shapeHeader && shapeHeader.batchType === 'metadata') {
36
- shapeHeader = (await shapeIterable.next()).value;
37
- }
38
- let dbfHeader = {};
39
- if (propertyIterable) {
40
- dbfHeader = (await propertyIterable.next()).value;
41
- if (dbfHeader && dbfHeader.batchType === 'metadata') {
42
- dbfHeader = (await propertyIterable.next()).value;
43
- }
44
- }
45
- let iterator;
46
- if (propertyIterable) {
47
- iterator = (0, zip_batch_iterators_1.zipBatchIterators)(shapeIterable, propertyIterable);
48
- }
49
- else {
50
- iterator = shapeIterable;
51
- }
52
- for await (const item of iterator) {
53
- let geometries;
54
- let properties;
55
- if (!propertyIterable) {
56
- geometries = item;
57
- }
58
- else {
59
- [geometries, properties] = item;
60
- }
61
- const geojsonGeometries = parseGeometries(geometries);
62
- let features = joinProperties(geojsonGeometries, properties);
63
- if (reproject) {
64
- // @ts-ignore
65
- features = reprojectFeatures(features, prj, _targetCrs);
66
- }
67
- yield {
68
- encoding: cpg,
69
- prj,
70
- shx,
71
- header: shapeHeader,
72
- data: features
73
- };
74
- }
75
- }
76
- exports.parseShapefileInBatches = parseShapefileInBatches;
77
- /**
78
- * Parse shapefile
79
- *
80
- * @param arrayBuffer
81
- * @param options
82
- * @param context
83
- * @returns output of shapefile
84
- */
85
- async function parseShapefile(arrayBuffer, options, context) {
86
- const { reproject = false, _targetCrs = 'WGS84' } = options?.gis || {};
87
- const { shx, cpg, prj } = await loadShapefileSidecarFiles(options, context);
88
- // parse geometries
89
- const { header, geometries } = await (0, loader_utils_1.parseFromContext)(arrayBuffer, shp_loader_1.SHPLoader, options, context); // {shp: shx}
90
- const geojsonGeometries = parseGeometries(geometries);
91
- // parse properties
92
- let properties = [];
93
- const dbfResponse = await context?.fetch(replaceExtension(context?.url, 'dbf'));
94
- if (dbfResponse?.ok) {
95
- properties = await (0, loader_utils_1.parseFromContext)(dbfResponse, dbf_loader_1.DBFLoader, { dbf: { encoding: cpg || 'latin1' } }, context);
96
- }
97
- let features = joinProperties(geojsonGeometries, properties);
98
- if (reproject) {
99
- features = reprojectFeatures(features, prj, _targetCrs);
100
- }
101
- return {
102
- encoding: cpg,
103
- prj,
104
- shx,
105
- header,
106
- data: features
107
- };
108
- }
109
- exports.parseShapefile = parseShapefile;
110
- /**
111
- * Parse geometries
112
- *
113
- * @param geometries
114
- * @returns geometries as an array
115
- */
116
- function parseGeometries(geometries) {
117
- const geojsonGeometries = [];
118
- for (const geom of geometries) {
119
- geojsonGeometries.push((0, gis_1.binaryToGeometry)(geom));
120
- }
121
- return geojsonGeometries;
122
- }
123
- /**
124
- * Join properties and geometries into features
125
- *
126
- * @param geometries [description]
127
- * @param properties [description]
128
- * @return [description]
129
- */
130
- function joinProperties(geometries, properties) {
131
- const features = [];
132
- for (let i = 0; i < geometries.length; i++) {
133
- const geometry = geometries[i];
134
- const feature = {
135
- type: 'Feature',
136
- geometry,
137
- // properties can be undefined if dbfResponse above was empty
138
- properties: (properties && properties[i]) || {}
139
- };
140
- features.push(feature);
141
- }
142
- return features;
143
- }
144
- /**
145
- * Reproject GeoJSON features to output CRS
146
- *
147
- * @param features parsed GeoJSON features
148
- * @param sourceCrs source coordinate reference system
149
- * @param targetCrs †arget coordinate reference system
150
- * @return Reprojected Features
151
- */
152
- function reprojectFeatures(features, sourceCrs, targetCrs) {
153
- if (!sourceCrs && !targetCrs) {
154
- return features;
155
- }
156
- const projection = new proj4_1.Proj4Projection({ from: sourceCrs || 'WGS84', to: targetCrs || 'WGS84' });
157
- return (0, gis_1.transformGeoJsonCoords)(features, (coord) => projection.project(coord));
158
- }
159
- /**
160
- *
161
- * @param options
162
- * @param context
163
- * @returns Promise
164
- */
165
- // eslint-disable-next-line max-statements
166
- async function loadShapefileSidecarFiles(options, context) {
167
- // Attempt a parallel load of the small sidecar files
168
- // @ts-ignore context must be defined
169
- const { url, fetch } = context;
170
- const shxPromise = fetch(replaceExtension(url, 'shx'));
171
- const cpgPromise = fetch(replaceExtension(url, 'cpg'));
172
- const prjPromise = fetch(replaceExtension(url, 'prj'));
173
- await Promise.all([shxPromise, cpgPromise, prjPromise]);
174
- let shx;
175
- let cpg;
176
- let prj;
177
- const shxResponse = await shxPromise;
178
- if (shxResponse.ok) {
179
- const arrayBuffer = await shxResponse.arrayBuffer();
180
- shx = (0, parse_shx_1.parseShx)(arrayBuffer);
181
- }
182
- const cpgResponse = await cpgPromise;
183
- if (cpgResponse.ok) {
184
- cpg = await cpgResponse.text();
185
- }
186
- const prjResponse = await prjPromise;
187
- if (prjResponse.ok) {
188
- prj = await prjResponse.text();
189
- }
190
- return {
191
- shx,
192
- cpg,
193
- prj
194
- };
195
- }
196
- exports.loadShapefileSidecarFiles = loadShapefileSidecarFiles;
197
- /**
198
- * Replace the extension at the end of a path.
199
- *
200
- * Matches the case of new extension with the case of the original file extension,
201
- * to increase the chance of finding files without firing off a request storm looking for various case combinations
202
- *
203
- * NOTE: Extensions can be both lower and uppercase
204
- * per spec, extensions should be lower case, but that doesn't mean they always are. See:
205
- * calvinmetcalf/shapefile-js#64, mapserver/mapserver#4712
206
- * https://trac.osgeo.org/mapserver/ticket/166
207
- */
208
- function replaceExtension(url, newExtension) {
209
- const baseName = basename(url);
210
- const extension = extname(url);
211
- const isUpperCase = extension === extension.toUpperCase();
212
- if (isUpperCase) {
213
- newExtension = newExtension.toUpperCase();
214
- }
215
- return `${baseName}.${newExtension}`;
216
- }
217
- exports.replaceExtension = replaceExtension;
218
- // NOTE - this gives the entire path minus extension (i.e. NOT same as path.basename)
219
- /**
220
- * @param url
221
- * @returns string
222
- */
223
- function basename(url) {
224
- const extIndex = url && url.lastIndexOf('.');
225
- if (typeof extIndex === 'number') {
226
- return extIndex >= 0 ? url.substr(0, extIndex) : '';
227
- }
228
- return extIndex;
229
- }
230
- /**
231
- * @param url
232
- * @returns string
233
- */
234
- function extname(url) {
235
- const extIndex = url && url.lastIndexOf('.');
236
- if (typeof extIndex === 'number') {
237
- return extIndex >= 0 ? url.substr(extIndex + 1) : '';
238
- }
239
- return extIndex;
240
- }
@@ -1,287 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.parseRecord = void 0;
4
- const LITTLE_ENDIAN = true;
5
- /**
6
- * Parse individual record
7
- *
8
- * @param view Record data
9
- * @return Binary Geometry Object
10
- */
11
- // eslint-disable-next-line complexity
12
- function parseRecord(view, options) {
13
- const { _maxDimensions = 4 } = options?.shp || {};
14
- let offset = 0;
15
- const type = view.getInt32(offset, LITTLE_ENDIAN);
16
- offset += Int32Array.BYTES_PER_ELEMENT;
17
- switch (type) {
18
- case 0:
19
- // Null Shape
20
- return parseNull();
21
- case 1:
22
- // Point
23
- return parsePoint(view, offset, Math.min(2, _maxDimensions));
24
- case 3:
25
- // PolyLine
26
- return parsePoly(view, offset, Math.min(2, _maxDimensions), 'LineString');
27
- case 5:
28
- // Polygon
29
- return parsePoly(view, offset, Math.min(2, _maxDimensions), 'Polygon');
30
- case 8:
31
- // MultiPoint
32
- return parseMultiPoint(view, offset, Math.min(2, _maxDimensions));
33
- // GeometryZ can have 3 or 4 dimensions, since the M is not required to
34
- // exist
35
- case 11:
36
- // PointZ
37
- return parsePoint(view, offset, Math.min(4, _maxDimensions));
38
- case 13:
39
- // PolyLineZ
40
- return parsePoly(view, offset, Math.min(4, _maxDimensions), 'LineString');
41
- case 15:
42
- // PolygonZ
43
- return parsePoly(view, offset, Math.min(4, _maxDimensions), 'Polygon');
44
- case 18:
45
- // MultiPointZ
46
- return parseMultiPoint(view, offset, Math.min(4, _maxDimensions));
47
- case 21:
48
- // PointM
49
- return parsePoint(view, offset, Math.min(3, _maxDimensions));
50
- case 23:
51
- // PolyLineM
52
- return parsePoly(view, offset, Math.min(3, _maxDimensions), 'LineString');
53
- case 25:
54
- // PolygonM
55
- return parsePoly(view, offset, Math.min(3, _maxDimensions), 'Polygon');
56
- case 28:
57
- // MultiPointM
58
- return parseMultiPoint(view, offset, Math.min(3, _maxDimensions));
59
- default:
60
- throw new Error(`unsupported shape type: ${type}`);
61
- }
62
- }
63
- exports.parseRecord = parseRecord;
64
- // TODO handle null
65
- /**
66
- * Parse Null geometry
67
- *
68
- * @return null
69
- */
70
- function parseNull() {
71
- return null;
72
- }
73
- /**
74
- * Parse point geometry
75
- *
76
- * @param view Geometry data
77
- * @param offset Offset in view
78
- * @param dim Dimension size
79
- */
80
- function parsePoint(view, offset, dim) {
81
- let positions;
82
- [positions, offset] = parsePositions(view, offset, 1, dim);
83
- return {
84
- positions: { value: positions, size: dim },
85
- type: 'Point'
86
- };
87
- }
88
- /**
89
- * Parse MultiPoint geometry
90
- *
91
- * @param view Geometry data
92
- * @param offset Offset in view
93
- * @param dim Input dimension
94
- * @return Binary geometry object
95
- */
96
- function parseMultiPoint(view, offset, dim) {
97
- // skip parsing box
98
- offset += 4 * Float64Array.BYTES_PER_ELEMENT;
99
- const nPoints = view.getInt32(offset, LITTLE_ENDIAN);
100
- offset += Int32Array.BYTES_PER_ELEMENT;
101
- let xyPositions = null;
102
- let mPositions = null;
103
- let zPositions = null;
104
- [xyPositions, offset] = parsePositions(view, offset, nPoints, 2);
105
- // Parse Z coordinates
106
- if (dim === 4) {
107
- // skip parsing range
108
- offset += 2 * Float64Array.BYTES_PER_ELEMENT;
109
- [zPositions, offset] = parsePositions(view, offset, nPoints, 1);
110
- }
111
- // Parse M coordinates
112
- if (dim >= 3) {
113
- // skip parsing range
114
- offset += 2 * Float64Array.BYTES_PER_ELEMENT;
115
- [mPositions, offset] = parsePositions(view, offset, nPoints, 1);
116
- }
117
- const positions = concatPositions(xyPositions, mPositions, zPositions);
118
- return {
119
- positions: { value: positions, size: dim },
120
- type: 'Point'
121
- };
122
- }
123
- /**
124
- * Polygon and PolyLine parsing
125
- *
126
- * @param view Geometry data
127
- * @param offset Offset in view
128
- * @param dim Input dimension
129
- * @param type Either 'Polygon' or 'Polyline'
130
- * @return Binary geometry object
131
- */
132
- // eslint-disable-next-line max-statements
133
- function parsePoly(view, offset, dim, type) {
134
- // skip parsing bounding box
135
- offset += 4 * Float64Array.BYTES_PER_ELEMENT;
136
- const nParts = view.getInt32(offset, LITTLE_ENDIAN);
137
- offset += Int32Array.BYTES_PER_ELEMENT;
138
- const nPoints = view.getInt32(offset, LITTLE_ENDIAN);
139
- offset += Int32Array.BYTES_PER_ELEMENT;
140
- // Create longer indices array by 1 because output format is expected to
141
- // include the last index as the total number of positions
142
- const bufferOffset = view.byteOffset + offset;
143
- const bufferLength = nParts * Int32Array.BYTES_PER_ELEMENT;
144
- const ringIndices = new Int32Array(nParts + 1);
145
- ringIndices.set(new Int32Array(view.buffer.slice(bufferOffset, bufferOffset + bufferLength)));
146
- ringIndices[nParts] = nPoints;
147
- offset += nParts * Int32Array.BYTES_PER_ELEMENT;
148
- let xyPositions = null;
149
- let mPositions = null;
150
- let zPositions = null;
151
- [xyPositions, offset] = parsePositions(view, offset, nPoints, 2);
152
- // Parse Z coordinates
153
- if (dim === 4) {
154
- // skip parsing range
155
- offset += 2 * Float64Array.BYTES_PER_ELEMENT;
156
- [zPositions, offset] = parsePositions(view, offset, nPoints, 1);
157
- }
158
- // Parse M coordinates
159
- if (dim >= 3) {
160
- // skip parsing range
161
- offset += 2 * Float64Array.BYTES_PER_ELEMENT;
162
- [mPositions, offset] = parsePositions(view, offset, nPoints, 1);
163
- }
164
- const positions = concatPositions(xyPositions, mPositions, zPositions);
165
- // parsePoly only accepts type = LineString or Polygon
166
- if (type === 'LineString') {
167
- return {
168
- type,
169
- positions: { value: positions, size: dim },
170
- pathIndices: { value: ringIndices, size: 1 }
171
- };
172
- }
173
- // for every ring, determine sign of polygon
174
- // Use only 2D positions for ring calc
175
- const polygonIndices = [];
176
- for (let i = 1; i < ringIndices.length; i++) {
177
- const startRingIndex = ringIndices[i - 1];
178
- const endRingIndex = ringIndices[i];
179
- // @ts-ignore
180
- const ring = xyPositions.subarray(startRingIndex * 2, endRingIndex * 2);
181
- const sign = getWindingDirection(ring);
182
- // A positive sign implies clockwise
183
- // A clockwise ring is a filled ring
184
- if (sign > 0) {
185
- polygonIndices.push(startRingIndex);
186
- }
187
- }
188
- polygonIndices.push(nPoints);
189
- return {
190
- type,
191
- positions: { value: positions, size: dim },
192
- primitivePolygonIndices: { value: ringIndices, size: 1 },
193
- // TODO: Dynamically choose Uint32Array over Uint16Array only when
194
- // necessary. I believe the implementation requires nPoints to be the
195
- // largest value in the array, so you should be able to use Uint32Array only
196
- // when nPoints > 65535.
197
- polygonIndices: { value: new Uint32Array(polygonIndices), size: 1 }
198
- };
199
- }
200
- /**
201
- * Parse a contiguous block of positions into a Float64Array
202
- *
203
- * @param view Geometry data
204
- * @param offset Offset in view
205
- * @param nPoints Number of points
206
- * @param dim Input dimension
207
- * @return Data and offset
208
- */
209
- function parsePositions(view, offset, nPoints, dim) {
210
- const bufferOffset = view.byteOffset + offset;
211
- const bufferLength = nPoints * dim * Float64Array.BYTES_PER_ELEMENT;
212
- return [
213
- new Float64Array(view.buffer.slice(bufferOffset, bufferOffset + bufferLength)),
214
- offset + bufferLength
215
- ];
216
- }
217
- /**
218
- * Concatenate and interleave positions arrays
219
- * xy positions are interleaved; mPositions, zPositions are their own arrays
220
- *
221
- * @param xyPositions 2d positions
222
- * @param mPositions M positions
223
- * @param zPositions Z positions
224
- * @return Combined interleaved positions
225
- */
226
- // eslint-disable-next-line complexity
227
- function concatPositions(xyPositions, mPositions, zPositions) {
228
- if (!(mPositions || zPositions)) {
229
- return xyPositions;
230
- }
231
- let arrayLength = xyPositions.length;
232
- let nDim = 2;
233
- if (zPositions && zPositions.length) {
234
- arrayLength += zPositions.length;
235
- nDim++;
236
- }
237
- if (mPositions && mPositions.length) {
238
- arrayLength += mPositions.length;
239
- nDim++;
240
- }
241
- const positions = new Float64Array(arrayLength);
242
- for (let i = 0; i < xyPositions.length / 2; i++) {
243
- positions[nDim * i] = xyPositions[i * 2];
244
- positions[nDim * i + 1] = xyPositions[i * 2 + 1];
245
- }
246
- if (zPositions && zPositions.length) {
247
- for (let i = 0; i < zPositions.length; i++) {
248
- // If Z coordinates exist; used as third coord in positions array
249
- positions[nDim * i + 2] = zPositions[i];
250
- }
251
- }
252
- if (mPositions && mPositions.length) {
253
- for (let i = 0; i < mPositions.length; i++) {
254
- // M is always last, either 3rd or 4th depending on if Z exists
255
- positions[nDim * i + (nDim - 1)] = mPositions[i];
256
- }
257
- }
258
- return positions;
259
- }
260
- /**
261
- * Returns the direction of the polygon path
262
- * A positive number is clockwise.
263
- * A negative number is counter clockwise.
264
- *
265
- * @param positions
266
- * @return Sign of polygon ring
267
- */
268
- function getWindingDirection(positions) {
269
- return Math.sign(getSignedArea(positions));
270
- }
271
- /**
272
- * Get signed area of flat typed array of 2d positions
273
- *
274
- * @param positions
275
- * @return Signed area of polygon ring
276
- */
277
- function getSignedArea(positions) {
278
- let area = 0;
279
- // Rings are closed according to shapefile spec
280
- const nCoords = positions.length / 2 - 1;
281
- for (let i = 0; i < nCoords; i++) {
282
- area +=
283
- (positions[i * 2] + positions[(i + 1) * 2]) *
284
- (positions[i * 2 + 1] - positions[(i + 1) * 2 + 1]);
285
- }
286
- return area / 2;
287
- }
@@ -1,43 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.parseSHPHeader = void 0;
4
- const LITTLE_ENDIAN = true;
5
- const BIG_ENDIAN = false;
6
- const SHP_MAGIC_NUMBER = 0x0000270a;
7
- /**
8
- * Extract the binary header
9
- * Note: Also used by SHX
10
- * @param headerView
11
- * @returns SHPHeader
12
- */
13
- function parseSHPHeader(headerView) {
14
- // Note: The SHP format switches endianness between fields!
15
- // https://www.esri.com/library/whitepapers/pdfs/shapefile.pdf
16
- const header = {
17
- magic: headerView.getInt32(0, BIG_ENDIAN),
18
- // Length is stored as # of 2-byte words; multiply by 2 to get # of bytes
19
- length: headerView.getInt32(24, BIG_ENDIAN) * 2,
20
- version: headerView.getInt32(28, LITTLE_ENDIAN),
21
- type: headerView.getInt32(32, LITTLE_ENDIAN),
22
- bbox: {
23
- minX: headerView.getFloat64(36, LITTLE_ENDIAN),
24
- minY: headerView.getFloat64(44, LITTLE_ENDIAN),
25
- minZ: headerView.getFloat64(68, LITTLE_ENDIAN),
26
- minM: headerView.getFloat64(84, LITTLE_ENDIAN),
27
- maxX: headerView.getFloat64(52, LITTLE_ENDIAN),
28
- maxY: headerView.getFloat64(60, LITTLE_ENDIAN),
29
- maxZ: headerView.getFloat64(76, LITTLE_ENDIAN),
30
- maxM: headerView.getFloat64(92, LITTLE_ENDIAN)
31
- }
32
- };
33
- if (header.magic !== SHP_MAGIC_NUMBER) {
34
- // eslint-disable-next-line
35
- console.error(`SHP file: bad magic number ${header.magic}`);
36
- }
37
- if (header.version !== 1000) {
38
- // eslint-disable-next-line
39
- console.error(`SHP file: bad version ${header.version}`);
40
- }
41
- return header;
42
- }
43
- exports.parseSHPHeader = parseSHPHeader;