shapefile.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505
  1. /*!
  2. * shapefile Version 0.6.6(https://github.com/mbostock/shapefile)
  3. * Copyright 2017 Mike Bostock.
  4. * mbostock/shapefile is licensed under the BSD 3-clause "New" or "Revised" License
  5. */
  6. (function (global, factory) {
  7. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  8. typeof define === 'function' && define.amd ? define(['exports'], factory) :
  9. (factory((global.shapefile = {})));
  10. }(this, (function (exports) { 'use strict';
  11. var array_cancel = function() {
  12. this._array = null;
  13. return Promise.resolve();
  14. };
  15. var array_read = function() {
  16. var array = this._array;
  17. this._array = null;
  18. return Promise.resolve(array ? {done: false, value: array} : {done: true, value: undefined});
  19. };
  20. function array(array) {
  21. return new ArraySource(array instanceof Uint8Array ? array : new Uint8Array(array));
  22. }
  23. function ArraySource(array) {
  24. this._array = array;
  25. }
  26. ArraySource.prototype.read = array_read;
  27. ArraySource.prototype.cancel = array_cancel;
  28. var fetchPath = function(url) {
  29. return fetch(url).then(function(response) {
  30. return response.body && response.body.getReader
  31. ? response.body.getReader()
  32. : response.arrayBuffer().then(array);
  33. });
  34. };
  35. var requestPath = function(url) {
  36. return new Promise(function(resolve, reject) {
  37. var request = new XMLHttpRequest;
  38. request.responseType = "arraybuffer";
  39. request.onload = function() { resolve(array(request.response)); };
  40. request.onerror = reject;
  41. request.ontimeout = reject;
  42. request.open("GET", url, true);
  43. request.send();
  44. });
  45. };
  46. function path(path) {
  47. return (typeof fetch === "function" ? fetchPath : requestPath)(path);
  48. }
  49. function stream(source) {
  50. return typeof source.read === "function" ? source : source.getReader();
  51. }
  52. var empty = new Uint8Array(0);
  53. var slice_cancel = function() {
  54. return this._source.cancel();
  55. };
  56. function concat(a, b) {
  57. if (!a.length) return b;
  58. if (!b.length) return a;
  59. var c = new Uint8Array(a.length + b.length);
  60. c.set(a);
  61. c.set(b, a.length);
  62. return c;
  63. }
  64. var slice_read = function() {
  65. var that = this, array = that._array.subarray(that._index);
  66. return that._source.read().then(function(result) {
  67. that._array = empty;
  68. that._index = 0;
  69. return result.done ? (array.length > 0
  70. ? {done: false, value: array}
  71. : {done: true, value: undefined})
  72. : {done: false, value: concat(array, result.value)};
  73. });
  74. };
  75. var slice_slice = function(length) {
  76. if ((length |= 0) < 0) throw new Error("invalid length");
  77. var that = this, index = this._array.length - this._index;
  78. // If the request fits within the remaining buffer, resolve it immediately.
  79. if (this._index + length <= this._array.length) {
  80. return Promise.resolve(this._array.subarray(this._index, this._index += length));
  81. }
  82. // Otherwise, read chunks repeatedly until the request is fulfilled.
  83. var array = new Uint8Array(length);
  84. array.set(this._array.subarray(this._index));
  85. return (function read() {
  86. return that._source.read().then(function(result) {
  87. // When done, it鈥檚 possible the request wasn鈥檛 fully fullfilled!
  88. // If so, the pre-allocated array is too big and needs slicing.
  89. if (result.done) {
  90. that._array = empty;
  91. that._index = 0;
  92. return index > 0 ? array.subarray(0, index) : null;
  93. }
  94. // If this chunk fulfills the request, return the resulting array.
  95. if (index + result.value.length >= length) {
  96. that._array = result.value;
  97. that._index = length - index;
  98. array.set(result.value.subarray(0, length - index), index);
  99. return array;
  100. }
  101. // Otherwise copy this chunk into the array, then read the next chunk.
  102. array.set(result.value, index);
  103. index += result.value.length;
  104. return read();
  105. });
  106. })();
  107. };
  108. function slice(source) {
  109. return typeof source.slice === "function" ? source :
  110. new SliceSource(typeof source.read === "function" ? source
  111. : source.getReader());
  112. }
  113. function SliceSource(source) {
  114. this._source = source;
  115. this._array = empty;
  116. this._index = 0;
  117. }
  118. SliceSource.prototype.read = slice_read;
  119. SliceSource.prototype.slice = slice_slice;
  120. SliceSource.prototype.cancel = slice_cancel;
  121. var dbf_cancel = function() {
  122. return this._source.cancel();
  123. };
  124. var readBoolean = function(value) {
  125. return /^[nf]$/i.test(value) ? false
  126. : /^[yt]$/i.test(value) ? true
  127. : null;
  128. };
  129. var readDate = function(value) {
  130. return new Date(+value.substring(0, 4), value.substring(4, 6) - 1, +value.substring(6, 8));
  131. };
  132. var readNumber = function(value) {
  133. return !(value = value.trim()) || isNaN(value = +value) ? null : value;
  134. };
  135. var readString = function(value) {
  136. return value.trim() || null;
  137. };
  138. var types = {
  139. B: readNumber,
  140. C: readString,
  141. D: readDate,
  142. F: readNumber,
  143. L: readBoolean,
  144. M: readNumber,
  145. N: readNumber
  146. };
  147. var dbf_read = function() {
  148. var that = this, i = 1;
  149. return that._source.slice(that._recordLength).then(function(value) {
  150. return value && (value[0] !== 0x1a) ? {done: false, value: that._fields.reduce(function(p, f) {
  151. p[f.name] = types[f.type](that._decode(value.subarray(i, i += f.length)));
  152. return p;
  153. }, {})} : {done: true, value: undefined};
  154. });
  155. };
  156. var view = function(array) {
  157. return new DataView(array.buffer, array.byteOffset, array.byteLength);
  158. };
  159. var dbf = function(source, decoder) {
  160. source = slice(source);
  161. return source.slice(32).then(function(array) {
  162. var head = view(array);
  163. return source.slice(head.getUint16(8, true) - 32).then(function(array) {
  164. return new Dbf(source, decoder, head, view(array));
  165. });
  166. });
  167. };
  168. function Dbf(source, decoder, head, body) {
  169. this._source = source;
  170. this._decode = decoder.decode.bind(decoder);
  171. this._recordLength = head.getUint16(10, true);
  172. this._fields = [];
  173. for (var n = 0; body.getUint8(n) !== 0x0d; n += 32) {
  174. for (var j = 0; j < 11; ++j) if (body.getUint8(n + j) === 0) break;
  175. this._fields.push({
  176. name: this._decode(new Uint8Array(body.buffer, body.byteOffset + n, j)),
  177. type: String.fromCharCode(body.getUint8(n + 11)),
  178. length: body.getUint8(n + 16)
  179. });
  180. }
  181. }
  182. var prototype = Dbf.prototype;
  183. prototype.read = dbf_read;
  184. prototype.cancel = dbf_cancel;
  185. function cancel() {
  186. return this._source.cancel();
  187. }
  188. var parseMultiPoint = function(record) {
  189. var i = 40, j, n = record.getInt32(36, true), coordinates = new Array(n);
  190. for (j = 0; j < n; ++j, i += 16) coordinates[j] = [record.getFloat64(i, true), record.getFloat64(i + 8, true)];
  191. return {type: "MultiPoint", coordinates: coordinates};
  192. };
  193. var parseNull = function() {
  194. return null;
  195. };
  196. var parsePoint = function(record) {
  197. return {type: "Point", coordinates: [record.getFloat64(4, true), record.getFloat64(12, true)]};
  198. };
  199. var parsePolygon = function(record) {
  200. var i = 44, j, n = record.getInt32(36, true), m = record.getInt32(40, true), parts = new Array(n), points = new Array(m), polygons = [], holes = [];
  201. for (j = 0; j < n; ++j, i += 4) parts[j] = record.getInt32(i, true);
  202. for (j = 0; j < m; ++j, i += 16) points[j] = [record.getFloat64(i, true), record.getFloat64(i + 8, true)];
  203. parts.forEach(function(i, j) {
  204. var ring = points.slice(i, parts[j + 1]);
  205. if (ringClockwise(ring)) polygons.push([ring]);
  206. else holes.push(ring);
  207. });
  208. holes.forEach(function(hole) {
  209. polygons.some(function(polygon) {
  210. if (ringContainsSome(polygon[0], hole)) {
  211. polygon.push(hole);
  212. return true;
  213. }
  214. }) || polygons.push([hole]);
  215. });
  216. return polygons.length === 1
  217. ? {type: "Polygon", coordinates: polygons[0]}
  218. : {type: "MultiPolygon", coordinates: polygons};
  219. };
  220. function ringClockwise(ring) {
  221. if ((n = ring.length) < 4) return false;
  222. var i = 0, n, area = ring[n - 1][1] * ring[0][0] - ring[n - 1][0] * ring[0][1];
  223. while (++i < n) area += ring[i - 1][1] * ring[i][0] - ring[i - 1][0] * ring[i][1];
  224. return area >= 0;
  225. }
  226. function ringContainsSome(ring, hole) {
  227. var i = -1, n = hole.length, c;
  228. while (++i < n) {
  229. if (c = ringContains(ring, hole[i])) {
  230. return c > 0;
  231. }
  232. }
  233. return false;
  234. }
  235. function ringContains(ring, point) {
  236. var x = point[0], y = point[1], contains = -1;
  237. for (var i = 0, n = ring.length, j = n - 1; i < n; j = i++) {
  238. var pi = ring[i], xi = pi[0], yi = pi[1],
  239. pj = ring[j], xj = pj[0], yj = pj[1];
  240. if (segmentContains(pi, pj, point)) {
  241. return 0;
  242. }
  243. if (((yi > y) !== (yj > y)) && ((x < (xj - xi) * (y - yi) / (yj - yi) + xi))) {
  244. contains = -contains;
  245. }
  246. }
  247. return contains;
  248. }
  249. function segmentContains(p0, p1, p2) {
  250. var x20 = p2[0] - p0[0], y20 = p2[1] - p0[1];
  251. if (x20 === 0 && y20 === 0) return true;
  252. var x10 = p1[0] - p0[0], y10 = p1[1] - p0[1];
  253. if (x10 === 0 && y10 === 0) return false;
  254. var t = (x20 * x10 + y20 * y10) / (x10 * x10 + y10 * y10);
  255. return t < 0 || t > 1 ? false : t === 0 || t === 1 ? true : t * x10 === x20 && t * y10 === y20;
  256. }
  257. var parsePolyLine = function(record) {
  258. var i = 44, j, n = record.getInt32(36, true), m = record.getInt32(40, true), parts = new Array(n), points = new Array(m);
  259. for (j = 0; j < n; ++j, i += 4) parts[j] = record.getInt32(i, true);
  260. for (j = 0; j < m; ++j, i += 16) points[j] = [record.getFloat64(i, true), record.getFloat64(i + 8, true)];
  261. return n === 1
  262. ? {type: "LineString", coordinates: points}
  263. : {type: "MultiLineString", coordinates: parts.map(function(i, j) { return points.slice(i, parts[j + 1]); })};
  264. };
  265. var concat$1 = function(a, b) {
  266. var ab = new Uint8Array(a.length + b.length);
  267. ab.set(a, 0);
  268. ab.set(b, a.length);
  269. return ab;
  270. };
  271. var shp_read = function() {
  272. var that = this;
  273. ++that._index;
  274. return that._source.slice(12).then(function(array) {
  275. if (array == null) return {done: true, value: undefined};
  276. var header = view(array);
  277. // If the record starts with an invalid shape type (see #36), scan ahead in
  278. // four-byte increments to find the next valid record, identified by the
  279. // expected index, a non-empty content length and a valid shape type.
  280. function skip() {
  281. return that._source.slice(4).then(function(chunk) {
  282. if (chunk == null) return {done: true, value: undefined};
  283. header = view(array = concat$1(array.slice(4), chunk));
  284. return header.getInt32(0, false) !== that._index ? skip() : read();
  285. });
  286. }
  287. // All records should have at least four bytes (for the record shape type),
  288. // so an invalid content length indicates corruption.
  289. function read() {
  290. var length = header.getInt32(4, false) * 2 - 4, type = header.getInt32(8, true);
  291. return length < 0 || (type && type !== that._type) ? skip() : that._source.slice(length).then(function(chunk) {
  292. return {done: false, value: type ? that._parse(view(concat$1(array.slice(8), chunk))) : null};
  293. });
  294. }
  295. return read();
  296. });
  297. };
  298. var parsers = {
  299. 0: parseNull,
  300. 1: parsePoint,
  301. 3: parsePolyLine,
  302. 5: parsePolygon,
  303. 8: parseMultiPoint,
  304. 11: parsePoint, // PointZ
  305. 13: parsePolyLine, // PolyLineZ
  306. 15: parsePolygon, // PolygonZ
  307. 18: parseMultiPoint, // MultiPointZ
  308. 21: parsePoint, // PointM
  309. 23: parsePolyLine, // PolyLineM
  310. 25: parsePolygon, // PolygonM
  311. 28: parseMultiPoint // MultiPointM
  312. };
  313. var shp = function(source) {
  314. source = slice(source);
  315. return source.slice(100).then(function(array) {
  316. return new Shp(source, view(array));
  317. });
  318. };
  319. function Shp(source, header) {
  320. var type = header.getInt32(32, true);
  321. if (!(type in parsers)) throw new Error("unsupported shape type: " + type);
  322. this._source = source;
  323. this._type = type;
  324. this._index = 0;
  325. this._parse = parsers[type];
  326. this.bbox = [header.getFloat64(36, true), header.getFloat64(44, true), header.getFloat64(52, true), header.getFloat64(60, true)];
  327. }
  328. var prototype$2 = Shp.prototype;
  329. prototype$2.read = shp_read;
  330. prototype$2.cancel = cancel;
  331. function noop() {}
  332. var shapefile_cancel = function() {
  333. return Promise.all([
  334. this._dbf && this._dbf.cancel(),
  335. this._shp.cancel()
  336. ]).then(noop);
  337. };
  338. var shapefile_read = function() {
  339. var that = this;
  340. return Promise.all([
  341. that._dbf ? that._dbf.read() : {value: {}},
  342. that._shp.read()
  343. ]).then(function(results) {
  344. var dbf = results[0], shp = results[1];
  345. return shp.done ? shp : {
  346. done: false,
  347. value: {
  348. type: "Feature",
  349. properties: dbf.value,
  350. geometry: shp.value
  351. }
  352. };
  353. });
  354. };
  355. var shapefile = function(shpSource, dbfSource, decoder) {
  356. return Promise.all([
  357. shp(shpSource),
  358. dbfSource && dbf(dbfSource, decoder)
  359. ]).then(function(sources) {
  360. return new Shapefile(sources[0], sources[1]);
  361. });
  362. };
  363. function Shapefile(shp$$1, dbf$$1) {
  364. this._shp = shp$$1;
  365. this._dbf = dbf$$1;
  366. this.bbox = shp$$1.bbox;
  367. }
  368. var prototype$1 = Shapefile.prototype;
  369. prototype$1.read = shapefile_read;
  370. prototype$1.cancel = shapefile_cancel;
  371. function open(shp$$1, dbf$$1, options) {
  372. if (typeof dbf$$1 === "string") {
  373. if (!/\.dbf$/.test(dbf$$1)) dbf$$1 += ".dbf";
  374. dbf$$1 = path(dbf$$1, options);
  375. } else if (dbf$$1 instanceof ArrayBuffer || dbf$$1 instanceof Uint8Array) {
  376. dbf$$1 = array(dbf$$1);
  377. } else if (dbf$$1 != null) {
  378. dbf$$1 = stream(dbf$$1);
  379. }
  380. if (typeof shp$$1 === "string") {
  381. if (!/\.shp$/.test(shp$$1)) shp$$1 += ".shp";
  382. if (dbf$$1 === undefined) dbf$$1 = path(shp$$1.substring(0, shp$$1.length - 4) + ".dbf", options).catch(function() {});
  383. shp$$1 = path(shp$$1, options);
  384. } else if (shp$$1 instanceof ArrayBuffer || shp$$1 instanceof Uint8Array) {
  385. shp$$1 = array(shp$$1);
  386. } else {
  387. shp$$1 = stream(shp$$1);
  388. }
  389. return Promise.all([shp$$1, dbf$$1]).then(function(sources) {
  390. var shp$$1 = sources[0], dbf$$1 = sources[1], encoding = "windows-1252";
  391. if (options && options.encoding != null) encoding = options.encoding;
  392. return shapefile(shp$$1, dbf$$1, dbf$$1 && new TextDecoder(encoding));
  393. });
  394. }
  395. function openShp(source, options) {
  396. if (typeof source === "string") {
  397. if (!/\.shp$/.test(source)) source += ".shp";
  398. source = path(source, options);
  399. } else if (source instanceof ArrayBuffer || source instanceof Uint8Array) {
  400. source = array(source);
  401. } else {
  402. source = stream(source);
  403. }
  404. return Promise.resolve(source).then(shp);
  405. }
  406. function openDbf(source, options) {
  407. var encoding = "windows-1252";
  408. if (options && options.encoding != null) encoding = options.encoding;
  409. encoding = new TextDecoder(encoding);
  410. if (typeof source === "string") {
  411. if (!/\.dbf$/.test(source)) source += ".dbf";
  412. source = path(source, options);
  413. } else if (source instanceof ArrayBuffer || source instanceof Uint8Array) {
  414. source = array(source);
  415. } else {
  416. source = stream(source);
  417. }
  418. return Promise.resolve(source).then(function(source) {
  419. return dbf(source, encoding);
  420. });
  421. }
  422. function read(shp$$1, dbf$$1, options) {
  423. return open(shp$$1, dbf$$1, options).then(function(source) {
  424. var features = [], collection = {type: "FeatureCollection", features: features, bbox: source.bbox};
  425. return source.read().then(function read(result) {
  426. if (result.done) return collection;
  427. features.push(result.value);
  428. return source.read().then(read);
  429. });
  430. });
  431. }
  432. exports.open = open;
  433. exports.openShp = openShp;
  434. exports.openDbf = openDbf;
  435. exports.read = read;
  436. Object.defineProperty(exports, '__esModule', { value: true });
  437. })));