index.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. // index.ts
  2. import { coordEach } from "@turf/meta";
  3. import { isNumber } from "@turf/helpers";
  4. import { clone } from "@turf/clone";
  5. function toMercator(geojson, options = {}) {
  6. return convert(geojson, "mercator", options);
  7. }
  8. function toWgs84(geojson, options = {}) {
  9. return convert(geojson, "wgs84", options);
  10. }
  11. function convert(geojson, projection, options = {}) {
  12. options = options || {};
  13. var mutate = options.mutate;
  14. if (!geojson) throw new Error("geojson is required");
  15. if (Array.isArray(geojson) && isNumber(geojson[0]))
  16. geojson = projection === "mercator" ? convertToMercator(geojson) : convertToWgs84(geojson);
  17. else {
  18. if (mutate !== true) geojson = clone(geojson);
  19. coordEach(geojson, function(coord) {
  20. var newCoord = projection === "mercator" ? convertToMercator(coord) : convertToWgs84(coord);
  21. coord[0] = newCoord[0];
  22. coord[1] = newCoord[1];
  23. });
  24. }
  25. return geojson;
  26. }
  27. function convertToMercator(lonLat) {
  28. var D2R = Math.PI / 180, A = 6378137, MAXEXTENT = 20037508342789244e-9;
  29. var adjusted = Math.abs(lonLat[0]) <= 180 ? lonLat[0] : lonLat[0] - sign(lonLat[0]) * 360;
  30. var xy = [
  31. A * adjusted * D2R,
  32. A * Math.log(Math.tan(Math.PI * 0.25 + 0.5 * lonLat[1] * D2R))
  33. ];
  34. if (xy[0] > MAXEXTENT) xy[0] = MAXEXTENT;
  35. if (xy[0] < -MAXEXTENT) xy[0] = -MAXEXTENT;
  36. if (xy[1] > MAXEXTENT) xy[1] = MAXEXTENT;
  37. if (xy[1] < -MAXEXTENT) xy[1] = -MAXEXTENT;
  38. return xy;
  39. }
  40. function convertToWgs84(xy) {
  41. var R2D = 180 / Math.PI;
  42. var A = 6378137;
  43. return [
  44. xy[0] * R2D / A,
  45. (Math.PI * 0.5 - 2 * Math.atan(Math.exp(-xy[1] / A))) * R2D
  46. ];
  47. }
  48. function sign(x) {
  49. return x < 0 ? -1 : x > 0 ? 1 : 0;
  50. }
  51. export {
  52. toMercator,
  53. toWgs84
  54. };
  55. //# sourceMappingURL=index.js.map