location.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. // utils/location.js
  2. const location = {
  3. /**
  4. * 获取地理位置(跨平台统一 Promise 版本)
  5. * @param {Object} options
  6. * type: 'wgs84' | 'gcj02' (默认 wgs84)
  7. * text: 授权提示文案 (默认 '需要获得您的位置,请您授权')
  8. * @returns {Promise} res: { latitude, longitude, speed, accuracy, ... }
  9. */
  10. get(options = {}) {
  11. const type = options.type || 'wgs84';
  12. const text = options.text || '需要获得您的位置,请您授权';
  13. return new Promise((resolve, reject) => {
  14. const doGet = () => {
  15. uni.getLocation({
  16. type,
  17. altitude: true,
  18. success(res) {
  19. resolve(res);
  20. },
  21. fail(err) {
  22. reject(err);
  23. }
  24. });
  25. };
  26. // H5 平台
  27. // #ifdef H5
  28. if (!navigator.geolocation) {
  29. reject({
  30. errMsg: '浏览器不支持定位'
  31. });
  32. return;
  33. }
  34. doGet();
  35. // #endif
  36. // App / 小程序平台
  37. // #ifndef H5
  38. uni.getSetting({
  39. success(res) {
  40. if (res.authSetting['scope.userLocation']) {
  41. doGet();
  42. } else {
  43. uni.authorize({
  44. scope: 'scope.userLocation',
  45. success() {
  46. doGet();
  47. },
  48. fail() {
  49. uni.showModal({
  50. title: '提示',
  51. content: text,
  52. showCancel: false,
  53. confirmText: '去授权',
  54. success() {
  55. uni.openSetting({
  56. success(setRes) {
  57. if (setRes.authSetting[
  58. 'scope.userLocation'
  59. ]) {
  60. doGet();
  61. } else {
  62. reject({
  63. errMsg: '用户未授权定位'
  64. });
  65. }
  66. },
  67. fail(err) {
  68. reject(err);
  69. }
  70. });
  71. }
  72. });
  73. }
  74. });
  75. }
  76. },
  77. fail(err) {
  78. reject(err);
  79. }
  80. });
  81. // #endif
  82. });
  83. }
  84. };
  85. export default location;