core.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. import proj from './Proj';
  2. import transform from './transform';
  3. var wgs84 = proj('WGS84');
  4. function transformer(from, to, coords, enforceAxis) {
  5. var transformedArray, out, keys;
  6. if (Array.isArray(coords)) {
  7. transformedArray = transform(from, to, coords, enforceAxis) || {x: NaN, y: NaN};
  8. if (coords.length > 2) {
  9. if ((typeof from.name !== 'undefined' && from.name === 'geocent') || (typeof to.name !== 'undefined' && to.name === 'geocent')) {
  10. if (typeof transformedArray.z === 'number') {
  11. return [transformedArray.x, transformedArray.y, transformedArray.z].concat(coords.splice(3));
  12. } else {
  13. return [transformedArray.x, transformedArray.y, coords[2]].concat(coords.splice(3));
  14. }
  15. } else {
  16. return [transformedArray.x, transformedArray.y].concat(coords.splice(2));
  17. }
  18. } else {
  19. return [transformedArray.x, transformedArray.y];
  20. }
  21. } else {
  22. out = transform(from, to, coords, enforceAxis);
  23. keys = Object.keys(coords);
  24. if (keys.length === 2) {
  25. return out;
  26. }
  27. keys.forEach(function (key) {
  28. if ((typeof from.name !== 'undefined' && from.name === 'geocent') || (typeof to.name !== 'undefined' && to.name === 'geocent')) {
  29. if (key === 'x' || key === 'y' || key === 'z') {
  30. return;
  31. }
  32. } else {
  33. if (key === 'x' || key === 'y') {
  34. return;
  35. }
  36. }
  37. out[key] = coords[key];
  38. });
  39. return out;
  40. }
  41. }
  42. function checkProj(item) {
  43. if (item instanceof proj) {
  44. return item;
  45. }
  46. if (item.oProj) {
  47. return item.oProj;
  48. }
  49. return proj(item);
  50. }
  51. function proj4(fromProj, toProj, coord) {
  52. fromProj = checkProj(fromProj);
  53. var single = false;
  54. var obj;
  55. if (typeof toProj === 'undefined') {
  56. toProj = fromProj;
  57. fromProj = wgs84;
  58. single = true;
  59. } else if (typeof toProj.x !== 'undefined' || Array.isArray(toProj)) {
  60. coord = toProj;
  61. toProj = fromProj;
  62. fromProj = wgs84;
  63. single = true;
  64. }
  65. toProj = checkProj(toProj);
  66. if (coord) {
  67. return transformer(fromProj, toProj, coord);
  68. } else {
  69. obj = {
  70. forward: function (coords, enforceAxis) {
  71. return transformer(fromProj, toProj, coords, enforceAxis);
  72. },
  73. inverse: function (coords, enforceAxis) {
  74. return transformer(toProj, fromProj, coords, enforceAxis);
  75. }
  76. };
  77. if (single) {
  78. obj.oProj = toProj;
  79. }
  80. return obj;
  81. }
  82. }
  83. export default proj4;