Utils.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. /*
  2. 205.395583333332 = 205°23'44.1"
  3. 1,直接读取"度":205
  4. 2,(205.395583333332-205)*60=23.734999999920 得到"分":23
  5. 3,(23.734999999920-23)*60=44.099999995200 得到"秒":44.1
  6. return string,
  7. */
  8. function latLngDecimalToDegrees(decimal) {
  9. let absDecimal = Math.abs(decimal);
  10. let isNegative = Math.abs(decimal) != decimal;
  11. let d = Math.floor(absDecimal); //度
  12. let m = Math.floor((absDecimal - d) * 60); //分
  13. let s = Math.round((absDecimal - d) * 3600 % 60); //秒
  14. if(s == 60) {s = 0; m++}
  15. if(m == 60) {m = 0; d++}
  16. //d = ('000'+d).slice(-3); // left-pad with leading zeros
  17. m = ('00'+m).slice(-2); // left-pad with leading zeros
  18. s = ('00'+s).slice(-2);
  19. //if (s<10) s = '0' + s; // left-pad with leading zeros (note may include decimals)
  20. return (isNegative ? "-" : "") + d + '°' + m + "′" + s + '″';
  21. }
  22. /*
  23. Decimal Degrees = Degrees + minutes/60 + seconds/3600
  24. 例:57°55'56.6" =57+55/60+56.6/3600=57.9323888888888
  25. return Float or NaN
  26. */
  27. function latLngDegreesToDecimal(degreesStr) {
  28. let degreesArr = degreesStr.split("°");
  29. let degrees = degreesArr[0];
  30. let isNegative = Math.abs(degrees) != degrees;
  31. if (degreesArr.length == 1) {
  32. return parseInt(degrees);
  33. }
  34. let minutesArr = degreesArr[1].split("′");
  35. let minutes = minutesArr[0];
  36. if (minutesArr.length == 1) {
  37. return parseFloat((isNegative ? "-" : "") + (Math.abs(degrees) + Math.abs(minutes) / 60));
  38. }
  39. let secondsStr = minutesArr[1];
  40. let secondsArr = secondsStr.split('″');
  41. let seconds = secondsArr[0];
  42. return parseFloat((isNegative ? "-" : "") + (Math.abs(degrees) + Math.abs(minutes) / 60 + Math.abs(seconds) / 3600));
  43. }
  44. function isObject(arg) {
  45. return typeof arg === 'object' && arg !== null;
  46. }
  47. function isUndefined(arg) {
  48. return arg === void 0;
  49. }
  50. function isString(arg) {
  51. return typeof arg === 'string';
  52. }
  53. function hasLine(obj) {
  54. return (isObject(obj)
  55. && isSafeString(obj.lat)
  56. && isSafeString(obj.lng));
  57. }
  58. function isSafeString(arg) {
  59. if (isUndefined(arg)) {
  60. return false;
  61. }
  62. if (!isString(arg)) {
  63. return false;
  64. }
  65. if (arg.length == 0) {
  66. return false;
  67. }
  68. return true;
  69. }
  70. function hasPoint(obj) {
  71. return (isObject(obj)
  72. && isSafeString(obj.lat)
  73. && isSafeString(obj.lng));
  74. }
  75. module.exports = {
  76. latLngDecimalToDegrees,
  77. latLngDegreesToDecimal,
  78. isObject,
  79. isUndefined,
  80. isString,
  81. isSafeString,
  82. hasLine,
  83. hasPoint
  84. }