收藏
回答

微信小程序可以获取用户GPS位置信息吗?

  // 新增方法:处理图片上传和展示

  handleImageUpload: function(imgpath, IDIndex) {

    const that = this;

    let hasHandled = false;

    const defaultLocation = { 

      longitude: 0, 

      latitude: 0,

      address: '未知位置' // 更友好的默认值

    };

  

    // 更健壮的地址获取方法

    const getLocationWithAddress = () => {

      return new Promise((resolve) => {

        wx.getLocation({

          type: "gcj02",

          isHighAccuracy: true,

          success: (locRes) => {

            // 单独处理地址获取,避免async/await在回调中的问题

            that.getReverseGeocoding(locRes.latitude, locRes.longitude)

              .then(address => {

                resolve({

                  longitude: locRes.longitude,

                  latitude: locRes.latitude,

                  address: address || defaultLocation.address

                });

              })

              .catch(() => {

                resolve({

                  longitude: locRes.longitude,

                  latitude: locRes.latitude,

                  address: defaultLocation.address

                });

              });

          },

          fail: () => {

            resolve(defaultLocation);

          }

        });

      });

    };

  

    // 设置超时(1.5秒)

    const timeoutPromise = new Promise(resolve => {

      setTimeout(() => resolve(defaultLocation), 1500);

    });

  

    Promise.race([getLocationWithAddress(), timeoutPromise])

      .then(location => {

        if (!hasHandled{

          hasHandled = true;

          console.log('最终位置数据:', location); // 调试日志

          that.showStuList(

            imgpath, 

            location.longitude, 

            location.latitude, 

            location.address,

            IDIndex

          );

        }

      })

      .catch(err => {

        console.error('位置获取异常:', err);

        if (!hasHandled{

          hasHandled = true;

          that.showStuList(

            imgpath, 

            defaultLocation.longitude, 

            defaultLocation.latitude, 

            defaultLocation.address,

            IDIndex

          );

        }

      });

  },

  

  // 修改后的逆地理编码方法

  getReverseGeocoding: function(lat, lng) {

    return new Promise((resolve, reject) => {

      if (!lat || !lng{

        reject('无效的坐标');

        return;

      }

  

      wx.request({

        url: `https://apis.map.qq.com/ws/geocoder/v1/?location=${lat},${lng}&key=HY5BZ-N3NKO-ZNZWK-SUFAN-4FSJV-YSFBJ`,

        success: (res) => {

          if (res.data && res.data.status === 0{

            resolve(res.data.result.address || '');

          } else {

            //reject(res.data?.message || '地址解析失败');

            reject((res.data && res.data.message|| '地址解析失败');

          }

        },

        fail: (err) => {

          reject('网络请求失败');

        }

      });

    });

  },


回答关注问题邀请回答
收藏

1 个回答

登录 后发表内容