index.js 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. import distance from '@turf/distance';
  2. /**
  3. * Takes a bounding box and calculates the minimum square bounding box that
  4. * would contain the input.
  5. *
  6. * @name square
  7. * @param {BBox} bbox extent in [west, south, east, north] order
  8. * @returns {BBox} a square surrounding `bbox`
  9. * @example
  10. * var bbox = [-20, -20, -15, 0];
  11. * var squared = turf.square(bbox);
  12. *
  13. * //addToMap
  14. * var addToMap = [turf.bboxPolygon(bbox), turf.bboxPolygon(squared)]
  15. */
  16. function square(bbox) {
  17. var west = bbox[0];
  18. var south = bbox[1];
  19. var east = bbox[2];
  20. var north = bbox[3];
  21. var horizontalDistance = distance(bbox.slice(0, 2), [east, south]);
  22. var verticalDistance = distance(bbox.slice(0, 2), [west, north]);
  23. if (horizontalDistance >= verticalDistance) {
  24. var verticalMidpoint = (south + north) / 2;
  25. return [
  26. west,
  27. verticalMidpoint - (east - west) / 2,
  28. east,
  29. verticalMidpoint + (east - west) / 2,
  30. ];
  31. } else {
  32. var horizontalMidpoint = (west + east) / 2;
  33. return [
  34. horizontalMidpoint - (north - south) / 2,
  35. south,
  36. horizontalMidpoint + (north - south) / 2,
  37. north,
  38. ];
  39. }
  40. }
  41. export default square;