bounds.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. import {hasOwnProperty} from "./object.js";
  2. // Computes the bounding box of the specified hash of GeoJSON objects.
  3. export default function(objects) {
  4. var x0 = Infinity,
  5. y0 = Infinity,
  6. x1 = -Infinity,
  7. y1 = -Infinity;
  8. function boundGeometry(geometry) {
  9. if (geometry != null && hasOwnProperty.call(boundGeometryType, geometry.type)) boundGeometryType[geometry.type](geometry);
  10. }
  11. var boundGeometryType = {
  12. GeometryCollection: function(o) { o.geometries.forEach(boundGeometry); },
  13. Point: function(o) { boundPoint(o.coordinates); },
  14. MultiPoint: function(o) { o.coordinates.forEach(boundPoint); },
  15. LineString: function(o) { boundLine(o.arcs); },
  16. MultiLineString: function(o) { o.arcs.forEach(boundLine); },
  17. Polygon: function(o) { o.arcs.forEach(boundLine); },
  18. MultiPolygon: function(o) { o.arcs.forEach(boundMultiLine); }
  19. };
  20. function boundPoint(coordinates) {
  21. var x = coordinates[0],
  22. y = coordinates[1];
  23. if (x < x0) x0 = x;
  24. if (x > x1) x1 = x;
  25. if (y < y0) y0 = y;
  26. if (y > y1) y1 = y;
  27. }
  28. function boundLine(coordinates) {
  29. coordinates.forEach(boundPoint);
  30. }
  31. function boundMultiLine(coordinates) {
  32. coordinates.forEach(boundLine);
  33. }
  34. for (var key in objects) {
  35. boundGeometry(objects[key]);
  36. }
  37. return x1 >= x0 && y1 >= y0 ? [x0, y0, x1, y1] : undefined;
  38. }