Przeglądaj źródła

feat: 处理高德地图不定位的问题

332777428@qq.com 6 miesięcy temu
rodzic
commit
ec0b21e436
1 zmienionych plików z 285 dodań i 189 usunięć
  1. 285 189
      src/pages/map/index.vue

+ 285 - 189
src/pages/map/index.vue

@@ -1,13 +1,22 @@
 <template>
-  <view class='app-container'>
+  <view class="app-container">
     <!-- 定位 + 城市选择器 -->
     <view class="tab" flex between>
-      <view class="address" @click="getRep">
-        <uni-icons :type="location === '定位中...' ? 'spinner-cycle' : 'location'" />
+      <!-- <view class="address" @click="getRep">
+        <uni-icons
+          :type="location === '定位中...' ? 'spinner-cycle' : 'location'"
+        />
         <text>{{ location }}</text>
-      </view>
-      <picker class="list" mode="multiSelector" :range="locationList" range-key="name" :value="pickerValue"
-        @columnchange="handleColumn" @change="handleChange">
+      </view> -->
+      <picker
+        class="list"
+        mode="multiSelector"
+        :range="locationList"
+        range-key="name"
+        :value="pickerValue"
+        @columnchange="handleColumn"
+        @change="handleChange"
+      >
         <view flex style="width: 100%">
           <view class="item" flex>
             <view class="name">{{ province }}</view>
@@ -25,12 +34,18 @@
       </picker>
     </view>
     <!-- 地图 -->
-    <view id="container" />
+    <!-- <view id="container" /> -->
     <!-- 范围内的门店 -->
     <scroll-view scroll-y class="poi" @scrolltolower="scrollTolower">
       <view v-if="list.length > 0" style="height: 100%; padding: 16px">
-        <view :class="['list', active === index ? 'active' : '']" flex center v-for="(item, index) in list" :key="item.id"
-          @click="changeActive(item, index)">
+        <view
+          :class="['list', active === index ? 'active' : '']"
+          flex
+          center
+          v-for="(item, index) in list"
+          :key="item.id"
+          @click="changeActive(item, index)"
+        >
           <img :src="item.icon" width="80" height="80" />
           <view class="info">
             <view class="name">{{ item.name }}</view>
@@ -38,13 +53,28 @@
             <view class="address">地址:{{ item.address }}</view>
           </view>
           <view class="button" flex around>
-            <img class="icon" v-show="item.linkPhone" src="../../static/phone.png" @click="getPhone(item.linkPhone)" />
-            <img class="icon" src="../../static/address.png" @click="getMap(item)" />
+            <img
+              class="icon"
+              v-show="item.linkPhone"
+              src="../../static/phone.png"
+              @click="getPhone(item.linkPhone)"
+            />
+            <img
+              class="icon"
+              src="../../static/address.png"
+              @click="getMap(item)"
+            />
           </view>
         </view>
       </view>
-      <view v-else style="height: 100%;  padding: 0 16px">
-        <view class="storeList" v-for="item in storeList" :key="item.id" flex between>
+      <view v-else style="height: 100%; padding: 0 16px">
+        <view
+          class="storeList"
+          v-for="item in storeList"
+          :key="item.id"
+          flex
+          between
+        >
           <img :src="item.icon" width="56" height="56" />
           <view class="info">
             <view class="name">{{ item.name }}</view>
@@ -57,7 +87,14 @@
     <uni-popup ref="popup" type="bottom">
       <view class="popup">
         <view class="title" flex center>请选择地图</view>
-        <view class="item" flex center v-for="item in mapList" :key="item.value" @click="openMap(item)">
+        <view
+          class="item"
+          flex
+          center
+          v-for="item in mapList"
+          :key="item.value"
+          @click="openMap(item)"
+        >
           {{ item.name }}
         </view>
       </view>
@@ -66,32 +103,35 @@
 </template>
 
 <script>
-import AMapLoader from '@amap/amap-jsapi-loader'
+import { list, options, storeList } from "@/api/map";
+import AMapLoader from "@amap/amap-jsapi-loader";
 // 安全密钥
 window._AMapSecurityConfig = {
-  securityJsCode: 'fd78b73eba80ab3f887c9ba60744048f'
-}
-import { options, list, storeList } from '@/api/map'
+  securityJsCode: "fd78b73eba80ab3f887c9ba60744048f",
+};
 export default {
   data() {
     return {
       // 是否为APP内部H5
       inside: getApp().globalData.inside,
       // 定位
-      location: '定位中...',
+      location: "定位中...",
       // 省市区列表
       locationList: [],
-      // 选中焦点 
+      // 选中焦点
       pickerValue: [18, 0, 0],
-      province: '',
-      city: '',
-      district: '',
+      province: "广东省",
+      city: "深圳市",
+      district: "南山区",
       // 表单
       form: {
         pageNum: 1,
         pageSize: 10,
         longitude: 116.397428,
-        latitude: 39.90923
+        latitude: 39.90923,
+        province: "440000",
+        city: "440300",
+        area: "440305",
       },
       // 线下店铺
       list: [],
@@ -100,139 +140,180 @@ export default {
       // 第三方店铺
       storeList: [],
       // 店铺坐标
-      toLng: '',
-      toLat: '',
-      toName: '',
+      toLng: "",
+      toLat: "",
+      toName: "",
 
       // 地图
       AMap: null,
       map: null,
       geolocation: null,
       // 地图App
-      mapList: [{
-        id: 1,
-        name: '腾讯地图',
-        value: 'qqMap'
-      }, {
-        id: 2,
-        name: '百度地图',
-        value: 'baiduMap'
-      }, {
-        id: 3,
-        name: '高德地图',
-        value: 'aMap'
-      }],
+      mapList: [
+        {
+          id: 1,
+          name: "腾讯地图",
+          value: "qqMap",
+        },
+        {
+          id: 2,
+          name: "百度地图",
+          value: "baiduMap",
+        },
+        {
+          id: 3,
+          name: "高德地图",
+          value: "aMap",
+        },
+      ],
       // 只触发一次
-      only: true
-    }
+      only: true,
+    };
   },
   onLoad() {
-    this.initAMap()
+    this.initAMap();
   },
   methods: {
     async initAMap() {
       // 调用高德
-      this.AMap = await this.getMapLoader()
-      // 自定义定位按钮
-      this.geolocation = new AMap.Geolocation({
-        timeout: 3000, // 定位超时时间
-        showCircle: false, // 定位成功有个圆形范围
-        showButton: false // 是否显示按钮
-      })
-      const locationRes = await this.getLocation(this.geolocation)
-      // 当前定位
-      if (locationRes.status === 'complete') {
-        this.form.longitude = locationRes.data.lng
-        this.form.latitude = locationRes.data.lat
-      }
-      // 获取城市信息
-      this.getGeocoder([this.form.longitude, this.form.latitude], locationRes.status)
-      // 绘制地图
-      this.map = new AMap.Map('container', {
-        zoom: 16,
-        center: [this.form.longitude, this.form.latitude]
-      })
-      // 调用插件
-      this.map.addControl(this.geolocation)
+      // this.AMap = await this.getMapLoader();
+      // // 自定义定位按钮
+      // this.geolocation = new AMap.Geolocation({
+      //   timeout: 3000, // 定位超时时间
+      //   showCircle: false, // 定位成功有个圆形范围
+      //   showButton: false, // 是否显示按钮
+      // });
+      // const locationRes = await this.getLocation(this.geolocation);
+      // // 当前定位
+      // if (locationRes.status === "complete") {
+      //   this.form.longitude = locationRes.data.lng;
+      //   this.form.latitude = locationRes.data.lat;
+      // }
+      // // 获取城市信息
+      // this.getGeocoder(
+      //   [this.form.longitude, this.form.latitude],
+      //   locationRes.status
+      // );
+      // // 绘制地图
+      // this.map = new AMap.Map("container", {
+      //   zoom: 16,
+      //   center: [this.form.longitude, this.form.latitude],
+      // });
+      // // 调用插件
+      // this.map.addControl(this.geolocation);
       // 地图加载完
-      this.map.on('complete', () => {
-        // 自动定位一次
-        this.geolocation.getCurrentPosition()
-      })
+      // this.map.on("complete", () => {
+      //   // 自动定位一次
+      //   this.geolocation.getCurrentPosition();
+      // });
+
+      var that = this;
+      options().then((res) => {
+        if (res.code === 0) {
+          let value = [];
+          // 市
+          that.locationList[0] = res.data;
+          value[0] = that.locationList[0].findIndex((i) => i);
+          that.locationList[1] = that.locationList[0][value[0]].childList;
+          value[1] = that.locationList[1].findIndex((i) => i);
+          // 省
+          if (value[1] !== -1) {
+            that.locationList[2] = that.locationList[1][value[1]].childList;
+          } else {
+          }
+          that.getList();
+        }
+      });
     },
 
     // 调用高德
     getMapLoader() {
       return new Promise((resolve, reject) => {
         AMapLoader.load({
-          key: '5dcf4cf0260059dade51d0d9b5e3c1ef',
-          version: '2.0',
-          plugins: ['AMap.Geolocation', 'AMap.Geocoder']
-        }).then((AMap) => {
-          resolve(AMap)
-        }).catch((err) => {
-          reject(err)
+          key: "5dcf4cf0260059dade51d0d9b5e3c1ef",
+          version: "2.0",
+          plugins: ["AMap.Geolocation", "AMap.Geocoder"],
         })
-      })
+          .then((AMap) => {
+            resolve(AMap);
+          })
+          .catch((err) => {
+            reject(err);
+          });
+      });
     },
 
     // 获取定位
     getLocation(geolocation) {
       return new Promise((resolve, reject) => {
-        this.AMap.plugin('AMap.Geolocation', function () {
+        this.AMap.plugin("AMap.Geolocation", function () {
           geolocation.getCurrentPosition(function (status, res) {
             resolve({
               status: status,
-              data: res.position
-            })
-          })
-        })
-      })
+              data: res.position,
+            });
+          });
+        });
+      });
     },
 
     // 获取城市信息
     async getGeocoder(lnglat, locationStatus) {
-      const that = this
-      this.AMap.plugin('AMap.Geocoder', function () {
-        var geocoder = new AMap.Geocoder()
+      const that = this;
+      this.AMap.plugin("AMap.Geocoder", function () {
+        var geocoder = new AMap.Geocoder();
         geocoder.getAddress(lnglat, function (status, resolve) {
-          if (status === 'complete' && resolve.info === 'OK' && resolve.regeocode.formattedAddress !== '中华人民共和国') {
-            let e = resolve.regeocode.addressComponent
-            that.location = locationStatus === 'complete' ? `${e.city ? e.city : e.province}${e.district}` : that.location = '重新定位'
-            that.form.city = null
-            that.city = '全部'
-            that.form.area = null
-            that.district = '全部'
-            that.locationList = []
-            options().then(res => {
+          if (
+            status === "complete" &&
+            resolve.info === "OK" &&
+            resolve.regeocode.formattedAddress !== "中华人民共和国"
+          ) {
+            let e = resolve.regeocode.addressComponent;
+            that.location =
+              locationStatus === "complete"
+                ? `${e.city ? e.city : e.province}${e.district}`
+                : (that.location = "重新定位");
+            that.form.city = null;
+            that.city = "全部";
+            that.form.area = null;
+            that.district = "全部";
+            that.locationList = [];
+            options().then((res) => {
               if (res.code === 0) {
-                let value = []
+                let value = [];
                 // 市
-                that.locationList[0] = res.data
-                value[0] = that.locationList[0].findIndex(i => e.province.includes(i.name))
-                that.form.province = that.locationList[0][value[0]].id
-                that.province = that.locationList[0][value[0]].name
-                that.locationList[1] = that.locationList[0][value[0]].childList
-                value[1] = that.locationList[1].findIndex(i => i.citycode === e.citycode)
+                that.locationList[0] = res.data;
+                value[0] = that.locationList[0].findIndex((i) =>
+                  e.province.includes(i.name)
+                );
+                that.form.province = that.locationList[0][value[0]].id;
+                that.province = that.locationList[0][value[0]].name;
+                that.locationList[1] = that.locationList[0][value[0]].childList;
+                value[1] = that.locationList[1].findIndex(
+                  (i) => i.citycode === e.citycode
+                );
                 // 省
                 if (value[1] !== -1) {
-                  that.form.city = that.locationList[1][value[1]].id
-                  that.city = that.locationList[1][value[1]].name
+                  that.form.city = that.locationList[1][value[1]].id;
+                  that.city = that.locationList[1][value[1]].name;
                   // 区
-                  that.locationList[2] = that.locationList[1][value[1]].childList
-                  value[2] = that.locationList[2].findIndex(i => i.adcode === e.adcode)
+                  that.locationList[2] =
+                    that.locationList[1][value[1]].childList;
+                  value[2] = that.locationList[2].findIndex(
+                    (i) => i.adcode === e.adcode
+                  );
                   if (value[2] !== -1) {
-                    that.form.area = that.locationList[2][value[2]].id
-                    that.district = that.locationList[2][value[2]].name
+                    that.form.area = that.locationList[2][value[2]].id;
+                    that.district = that.locationList[2][value[2]].name;
                   }
                 }
-                that.pickerValue = value
-                that.getList()
+                that.pickerValue = value;
+                that.getList();
               }
-            })
+            });
           }
-        })
-      })
+        });
+      });
     },
 
     // 添加标点
@@ -240,167 +321,181 @@ export default {
       const icon = new AMap.Icon({
         size: new AMap.Size(30, 30),
         imageSize: new AMap.Size(30, 30),
-        image: '../../static/location.png'
-      })
+        image: "../../static/location.png",
+      });
       const marker = new AMap.Marker({
         position: new AMap.LngLat(lng, lat),
         offset: new AMap.Pixel(-20, -25),
-        icon: icon
-      })
-      this.map.add(marker)
+        icon: icon,
+      });
+      this.map.add(marker);
     },
 
     // 打开地图
     openMap(e) {
-      this.$refs.popup.close()
-      let url = ''
+      this.$refs.popup.close();
+      let url = "";
       if (this.inside) {
-        openOtherApp.postMessage(`?page=${e.value}&longitude=${this.toLng}&latitude=${this.toLat}&name=${this.toName}`)
+        openOtherApp.postMessage(
+          `?page=${e.value}&longitude=${this.toLng}&latitude=${this.toLat}&name=${this.toName}`
+        );
       } else {
         // 腾讯地图
         if (e.id === 1) {
-          url = `https://apis.map.qq.com/uri/v1/routeplan?type=drive&from=我的位置&fromcoord=${this.form.latitude},${this.form.longitude}&to=${this.toName}&tocoord=${this.toLat},${this.toLng}&coord_type=2&referer=猫王妙播Pro`
+          url = `https://apis.map.qq.com/uri/v1/routeplan?type=drive&from=我的位置&fromcoord=${this.form.latitude},${this.form.longitude}&to=${this.toName}&tocoord=${this.toLat},${this.toLng}&coord_type=2&referer=猫王妙播Pro`;
         }
 
         // 百度地图
         if (e.id === 2) {
-          url = `http://api.map.baidu.com/direction?origin=latlng:${this.form.latitude},${this.form.longitude}|name:我的位置&destination=latlng:${this.toLat},${this.toLng}|name:${this.toName}&mode=driving&region=${this.province}&output=html&coord_type=gcj02&src=webapp.airsmart.猫王妙播Pro`
+          url = `http://api.map.baidu.com/direction?origin=latlng:${this.form.latitude},${this.form.longitude}|name:我的位置&destination=latlng:${this.toLat},${this.toLng}|name:${this.toName}&mode=driving&region=${this.province}&output=html&coord_type=gcj02&src=webapp.airsmart.猫王妙播Pro`;
         }
 
         // 高德地图
         if (e.id === 3) {
-          url = `https://uri.amap.com/navigation?from=${this.form.longitude},${this.form.latitude},我的位置&to=${this.toLng},${this.toLat},${this.toName}&callnative=1`
+          url = `https://uri.amap.com/navigation?from=${this.form.longitude},${this.form.latitude},我的位置&to=${this.toLng},${this.toLat},${this.toName}&callnative=1`;
         }
-        window.location.href = url
+        window.location.href = url;
       }
     },
 
     // 重新定位
     getRep() {
-      this.location = '定位中...'
-      this.initAMap()
+      this.location = "定位中...";
+      this.initAMap();
     },
 
     // 选择省
     handleColumn(e) {
-      let column = e.detail.column
-      let index = e.detail.value
+      console.log("gadsfqwrqwrq=11==" + JSON.stringify(e));
+      let column = e.detail.column;
+      let index = e.detail.value;
       if (column === 0) {
-        this.pickerValue = [index, 0, 0]
-        this.locationList[1] = this.locationList[0][index].childList
-        this.locationList[2] = this.locationList[1].length > 0 ? this.locationList[1][0].childList : []
+        this.pickerValue = [index, 0, 0];
+        this.locationList[1] = this.locationList[0][index].childList;
+        this.locationList[2] =
+          this.locationList[1].length > 0
+            ? this.locationList[1][0].childList
+            : [];
       }
       if (column === 1) {
-        this.pickerValue = [this.pickerValue[0], index, 0]
-        this.locationList[2] = this.locationList[1][index].childList
+        this.pickerValue = [this.pickerValue[0], index, 0];
+        this.locationList[2] = this.locationList[1][index].childList;
       }
     },
 
     // 确定
     handleChange(e) {
-      this.form.province = ''
-      this.form.city = ''
-      this.city = '全部'
-      this.form.area = ''
-      this.district = '全部'
-      let index = e.detail.value
-      this.form.province = this.locationList[0][index[0]].id
-      this.province = this.locationList[0][index[0]].name
+      this.form.province = "";
+      this.form.city = "";
+      this.city = "全部";
+      this.form.area = "";
+      this.district = "全部";
+      let index = e.detail.value;
+      this.form.province = this.locationList[0][index[0]].id;
+      this.province = this.locationList[0][index[0]].name;
       if (this.locationList[1].length > 0) {
-        this.form.city = this.locationList[1][index[1]].id
-        this.city = this.locationList[1][index[1]].name
+        this.form.city = this.locationList[1][index[1]].id;
+        this.city = this.locationList[1][index[1]].name;
       }
       if (this.locationList[2].length > 0) {
-        this.form.area = this.locationList[2][index[2]].id
-        this.district = this.locationList[2][index[2]].name
+        this.form.area = this.locationList[2][index[2]].id;
+        this.district = this.locationList[2][index[2]].name;
       }
-      this.getList()
+      console.log("gadsfqwrqwrq=00==" + JSON.stringify(this.locationList));
+      this.getList();
     },
 
     // 线下店铺
     getList() {
-      this.list = []
-      this.storeList = []
-      this.map.clearMap()
-      list(this.form).then(res => {
+      this.list = [];
+      this.storeList = [];
+      // this.map.clearMap();
+
+      // this.form {"pageNum":1,"pageSize":10,"longitude":116.397428,"latitude":39.90923,
+      // "city":"110100","area":"110101","province":"110000"}
+      // this.form.province = this.province;
+      // this.form.city = this.city;
+      // this.form.area = this.district;
+      console.log("gadsfqwrqwrq=333==" + JSON.stringify(this.form));
+      list(this.form).then((res) => {
+        console.log("gadsfqwrqwrq=22==" + JSON.stringify(res));
         if (res.code === 0) {
           if (res.data.records.length > 0) {
-            res.data.records.map(i => {
-              this.list.push(i)
-              this.getMarker(i.longitude, i.latitude)
-            })
-            this.hasMore = res.data.hasMore
-            this.map.setCenter([this.list[0].longitude, this.list[0].latitude])
+            res.data.records.map((i) => {
+              this.list.push(i);
+              this.getMarker(i.longitude, i.latitude);
+            });
+            this.hasMore = res.data.hasMore;
+            this.map.setCenter([this.list[0].longitude, this.list[0].latitude]);
           } else {
-            this.getStoreList()
+            this.getStoreList();
           }
         }
-      })
+      });
     },
 
     // 切换店铺
     changeActive(item, index) {
-      this.active = index
-      this.map.setZoom(16)
-      this.map.setCenter([item.longitude, item.latitude])
+      this.active = index;
+      this.map.setZoom(16);
+      this.map.setCenter([item.longitude, item.latitude]);
     },
 
-
     // 第三方店铺
     getStoreList() {
-      storeList().then(res => {
+      storeList().then((res) => {
         if (res.code === 0) {
-          this.storeList = res.data
+          this.storeList = res.data;
         }
-      })
+      });
     },
 
     // 跳转第三方店铺
     getStore(url) {
       if (this.inside) {
-        openOtherApp.postMessage(`?page=openOtherWeb&url=${url}`)
+        openOtherApp.postMessage(`?page=openOtherWeb&url=${url}`);
       } else {
-        window.location.href = url
+        window.location.href = url;
       }
     },
 
     // 拨打电话
     getPhone(e) {
       if (this.inside) {
-        openOtherApp.postMessage(`?page=callPhone&name=${e}`)
+        openOtherApp.postMessage(`?page=callPhone&name=${e}`);
       } else {
         uni.makePhoneCall({
-          phoneNumber: e
-        })
+          phoneNumber: e,
+        });
       }
     },
 
     // 打开地图
     getMap(e) {
-      this.$refs.popup.open()
+      this.$refs.popup.open();
       // 店铺坐标
-      this.toLng = e.longitude
-      this.toLat = e.latitude
-      this.toName = e.name
+      this.toLng = e.longitude;
+      this.toLat = e.latitude;
+      this.toName = e.name;
     },
 
     // 触底
     scrollTolower() {
       if (this.hasMore) {
-        this.form.pageNum++
-        this.getList()
+        this.form.pageNum++;
+        this.getList();
       } else {
         if (this.only) {
           uni.showToast({
-            icon: 'none',
-            title: '暂无更多店铺'
-          })
-          this.only = false
+            icon: "none",
+            title: "暂无更多店铺",
+          });
+          this.only = false;
         }
       }
-    }
-  }
-}
+    },
+  },
+};
 </script>
 
 <style lang="scss" scoped>
@@ -420,7 +515,7 @@ export default {
     height: 88rpx;
     line-height: 88rpx;
     padding: 0 12px;
-    background-color: #FFF;
+    background-color: #fff;
     white-space: nowrap;
 
     .address {
@@ -456,10 +551,11 @@ export default {
 
   .poi {
     width: 100%;
-    height: 270px;
+    height: 100%;
+    // height: 270px;
     overflow-y: auto;
     z-index: 99;
-    background-color: #FFF;
+    background-color: #fff;
 
     .list,
     .storeList {
@@ -525,7 +621,7 @@ export default {
     }
 
     .active {
-      background-color: #F2F5F7;
+      background-color: #f2f5f7;
     }
   }
 
@@ -539,7 +635,7 @@ export default {
 
   .popup {
     width: 90%;
-    background-color: #FFF;
+    background-color: #fff;
     border-radius: 16px;
     margin: 0 auto;
     position: absolute;