uniMap.vue 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. <template></template>
  2. <script>
  3. import { getAddressCode } from "@/api/address";
  4. import config from '@/config/config'
  5. export default {
  6. data() {
  7. return {
  8. config
  9. };
  10. },
  11. mounted() {
  12. this.init();
  13. },
  14. methods: {
  15. // 初始化地图并且调用
  16. initMap() {
  17. let that = this;
  18. uni.chooseLocation({
  19. success: function (res) {
  20. /**获取地址详情地址 */
  21. that.posToCity(res.latitude, res.longitude).then((val) => {
  22. /**获取地址code */
  23. getAddressCode(
  24. val.regeocode.addressComponent.citycode,
  25. val.regeocode.addressComponent.township
  26. ).then((code) => {
  27. that.$emit("callback", { ...val, ...res, ...code });
  28. that.$emit("close");
  29. });
  30. });
  31. },
  32. fail() {
  33. that.$emit("close");
  34. },
  35. });
  36. },
  37. // 根据当前客户端判断展示不同类型数据
  38. init() {
  39. // #ifdef MP-WEIXIN
  40. this.wechatMap();
  41. // #endif
  42. // #ifndef MP-WEIXIN
  43. this.initMap();
  44. // #endif
  45. },
  46. // 如果是微信小程序单独走微信小程序授权模式
  47. wechatMap() {
  48. let that = this;
  49. uni.authorize({
  50. scope: "scope.userLocation",
  51. success() {
  52. // 允许授权
  53. that.initMap();
  54. },
  55. fail() {
  56. //拒绝授权
  57. uni.showModal({
  58. content: "检测到您没打开获取地址功能权限,是否去设置打开?",
  59. confirmText: "确认",
  60. cancelText: "取消",
  61. success: (res) => {
  62. if (res.confirm) {
  63. // 打开设置好后重新刷新地图
  64. uni.openSetting({
  65. success: (res) => {
  66. that.initMap();
  67. },
  68. });
  69. } else {
  70. // 取消后关闭
  71. that.$emit("close");
  72. return false;
  73. }
  74. },
  75. });
  76. return false;
  77. },
  78. });
  79. },
  80. // 获取城市的数据
  81. posToCity(latitude, longitude) {
  82. return new Promise((resolve, reject) => {
  83. uni.request({
  84. url: `https://restapi.amap.com/v3/geocode/regeo`,
  85. method: "GET",
  86. data: {
  87. key: config.aMapKey, //web服务的key
  88. location: `${longitude},${latitude}`,
  89. },
  90. success: ({ data }) => {
  91. const { status, info } = data;
  92. if (status === "1") {
  93. resolve(data);
  94. } else {
  95. reject(info);
  96. }
  97. },
  98. fail: (err) => {
  99. reject(err);
  100. },
  101. });
  102. });
  103. },
  104. },
  105. };
  106. </script>
  107. <style lang="scss" scoped>
  108. </style>