address.ts 3.1 KB

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