extract.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. import {hasOwnProperty} from "./object.js";
  2. // Extracts the lines and rings from the specified hash of geometry objects.
  3. //
  4. // Returns an object with three properties:
  5. //
  6. // * coordinates - shared buffer of [x, y] coordinates
  7. // * lines - lines extracted from the hash, of the form [start, end]
  8. // * rings - rings extracted from the hash, of the form [start, end]
  9. //
  10. // For each ring or line, start and end represent inclusive indexes into the
  11. // coordinates buffer. For rings (and closed lines), coordinates[start] equals
  12. // coordinates[end].
  13. //
  14. // For each line or polygon geometry in the input hash, including nested
  15. // geometries as in geometry collections, the `coordinates` array is replaced
  16. // with an equivalent `arcs` array that, for each line (for line string
  17. // geometries) or ring (for polygon geometries), points to one of the above
  18. // lines or rings.
  19. export default function(objects) {
  20. var index = -1,
  21. lines = [],
  22. rings = [],
  23. coordinates = [];
  24. function extractGeometry(geometry) {
  25. if (geometry && hasOwnProperty.call(extractGeometryType, geometry.type)) extractGeometryType[geometry.type](geometry);
  26. }
  27. var extractGeometryType = {
  28. GeometryCollection: function(o) { o.geometries.forEach(extractGeometry); },
  29. LineString: function(o) { o.arcs = extractLine(o.arcs); },
  30. MultiLineString: function(o) { o.arcs = o.arcs.map(extractLine); },
  31. Polygon: function(o) { o.arcs = o.arcs.map(extractRing); },
  32. MultiPolygon: function(o) { o.arcs = o.arcs.map(extractMultiRing); }
  33. };
  34. function extractLine(line) {
  35. for (var i = 0, n = line.length; i < n; ++i) coordinates[++index] = line[i];
  36. var arc = {0: index - n + 1, 1: index};
  37. lines.push(arc);
  38. return arc;
  39. }
  40. function extractRing(ring) {
  41. for (var i = 0, n = ring.length; i < n; ++i) coordinates[++index] = ring[i];
  42. var arc = {0: index - n + 1, 1: index};
  43. rings.push(arc);
  44. return arc;
  45. }
  46. function extractMultiRing(rings) {
  47. return rings.map(extractRing);
  48. }
  49. for (var key in objects) {
  50. extractGeometry(objects[key]);
  51. }
  52. return {
  53. type: "Topology",
  54. coordinates: coordinates,
  55. lines: lines,
  56. rings: rings,
  57. objects: objects
  58. };
  59. }