1
0

shapefile.js 15 KB

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