index.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. import centroid from '@turf/centroid';
  2. import rhumbBearing from '@turf/rhumb-bearing';
  3. import rhumbDistance from '@turf/rhumb-distance';
  4. import rhumbDestination from '@turf/rhumb-destination';
  5. import clone from '@turf/clone';
  6. import { coordEach } from '@turf/meta';
  7. import { getCoords } from '@turf/invariant';
  8. import { isObject } from '@turf/helpers';
  9. /**
  10. * Rotates any geojson Feature or Geometry of a specified angle, around its `centroid` or a given `pivot` point.
  11. *
  12. * @name transformRotate
  13. * @param {GeoJSON} geojson object to be rotated
  14. * @param {number} angle of rotation in decimal degrees, positive clockwise
  15. * @param {Object} [options={}] Optional parameters
  16. * @param {Coord} [options.pivot='centroid'] point around which the rotation will be performed
  17. * @param {boolean} [options.mutate=false] allows GeoJSON input to be mutated (significant performance increase if true)
  18. * @returns {GeoJSON} the rotated GeoJSON feature
  19. * @example
  20. * var poly = turf.polygon([[[0,29],[3.5,29],[2.5,32],[0,29]]]);
  21. * var options = {pivot: [0, 25]};
  22. * var rotatedPoly = turf.transformRotate(poly, 10, options);
  23. *
  24. * //addToMap
  25. * var addToMap = [poly, rotatedPoly];
  26. * rotatedPoly.properties = {stroke: '#F00', 'stroke-width': 4};
  27. */
  28. function transformRotate(geojson, angle, options) {
  29. // Optional parameters
  30. options = options || {};
  31. if (!isObject(options)) throw new Error("options is invalid");
  32. var pivot = options.pivot;
  33. var mutate = options.mutate;
  34. // Input validation
  35. if (!geojson) throw new Error("geojson is required");
  36. if (angle === undefined || angle === null || isNaN(angle))
  37. throw new Error("angle is required");
  38. // Shortcut no-rotation
  39. if (angle === 0) return geojson;
  40. // Use centroid of GeoJSON if pivot is not provided
  41. if (!pivot) pivot = centroid(geojson);
  42. // Clone geojson to avoid side effects
  43. if (mutate === false || mutate === undefined) geojson = clone(geojson);
  44. // Rotate each coordinate
  45. coordEach(geojson, function (pointCoords) {
  46. var initialAngle = rhumbBearing(pivot, pointCoords);
  47. var finalAngle = initialAngle + angle;
  48. var distance = rhumbDistance(pivot, pointCoords);
  49. var newCoords = getCoords(rhumbDestination(pivot, distance, finalAngle));
  50. pointCoords[0] = newCoords[0];
  51. pointCoords[1] = newCoords[1];
  52. });
  53. return geojson;
  54. }
  55. export default transformRotate;