address.ts 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. import { defineStore } from 'pinia'
  2. interface addressState {
  3. Location: {
  4. /**
  5. * 纬度
  6. */
  7. latitude: number | null
  8. /**
  9. * 经度
  10. */
  11. longitude: number | null
  12. }
  13. name: string
  14. city: string
  15. }
  16. export const useAddressStore = defineStore('address', {
  17. state: (): addressState => ({
  18. Location: {
  19. latitude: null,
  20. longitude: null,
  21. },
  22. name: '请选择位置',
  23. city: '',
  24. }),
  25. actions: {
  26. // 获取地理位置的函数
  27. getLocation() {
  28. uni.showLoading({ mask: true })
  29. // 1. 检查当前授权状态
  30. uni.getSetting({
  31. success: (res) => {
  32. const locationAuth = res.authSetting['scope.userLocation']
  33. // 2. 已授权 - 直接获取位置
  34. if (locationAuth) {
  35. this.fetchActualLocation()
  36. uni.hideLoading()
  37. }
  38. // 3. 未授权 - 尝试请求授权
  39. else {
  40. uni.authorize({
  41. scope: 'scope.userLocation',
  42. success: () => this.fetchActualLocation(),
  43. fail: () => this.showAuthGuide(), // 用户拒绝,显示引导
  44. complete: () => uni.hideLoading(),
  45. })
  46. }
  47. },
  48. })
  49. },
  50. // 实际获取位置的方法
  51. fetchActualLocation() {
  52. uni.getLocation({
  53. type: 'wgs84',
  54. isHighAccuracy: true,
  55. altitude: true,
  56. success: (res) => {
  57. console.log('位置获取成功', res)
  58. this.Location.latitude = res.latitude
  59. this.Location.longitude = res.longitude
  60. },
  61. fail: (err) => {
  62. console.log(err, '获取位置失败')
  63. if (err.errMsg === 'getLocation:fail system permission denied') {
  64. useGlobalToast().show('手机定位权限未打开,请手动在设置里面打开定位')
  65. }
  66. else {
  67. useGlobalToast().show(`获取定位失败:${err.errMsg}`)
  68. }
  69. },
  70. })
  71. },
  72. // 显示授权引导
  73. showAuthGuide() {
  74. uni.showModal({
  75. title: '需要位置权限',
  76. content: '请开启位置授权以使用完整功能',
  77. confirmText: '去设置',
  78. success: (res) => {
  79. if (res.confirm) {
  80. // 4. 用户点击确认后打开设置页
  81. wx.openSetting({
  82. success: (settingRes) => {
  83. // 5. 检查用户是否在设置页中开启了授权
  84. if (settingRes.authSetting['scope.userLocation']) {
  85. this.fetchActualLocation()
  86. }
  87. else {
  88. console.log('用户仍未授权')
  89. }
  90. },
  91. })
  92. }
  93. },
  94. })
  95. },
  96. getMapAddress() {
  97. uni.chooseLocation({
  98. success: (res) => {
  99. console.log(res, '收获地址')
  100. this.Location.latitude = res.latitude
  101. this.Location.longitude = res.longitude
  102. this.name = res.name
  103. },
  104. fail: (e) => {
  105. console.log('获取地址失败', e)
  106. },
  107. })
  108. },
  109. },
  110. })