在微信小程序中实现简单的位置获取以及地图显示

首先你需要在页面上微信自带的腾讯地图控件

<view>
  //地图控件
  <map id="myMap" 
        //纬度
       :latitude="latitude" 
        //经度
       :longitude="longitude" 
        //地图区域显示,数字越大显示的越细节的城市,数字越小,显示的区域越大
       scale="16"
       show-location
       style="width: 100%; height: 1200rpx;">
  </map>
</view>

在对应的js文件中,你需要通过微信api获取你自己所在的位置经纬度,然后把位置经纬度动态的给到 latitude ,longitude,必须加上刷新地图控件这个东西,不加的话为导致,地图先渲染出来之后,视图区域看到的不是你现在所在的位置
    // 强制更新地图组件
    this.updateMap();

Page({
  data: {
    latitude: 39.9042, // 北京的默认纬度
    longitude: 116.4074, // 北京的默认经度
  },

  onLoad: function () {
    this.checkLocationPermission();
  },

  checkLocationPermission: function () {
    wx.getSetting({
      success: res => {
        if (!res.authSetting['scope.userLocation']) {
          this.requestLocationPermission();
        } else {
          this.getLocation();
        }
      }
    });
  },

  requestLocationPermission: function () {
    wx.authorize({
      scope: 'scope.userLocation',
      success: () => {
        this.getLocation();
      },
      fail: () => {
        wx.showModal({
          title: '提示',
          content: '需要获取您的位置,请允许授权',
          showCancel: false,
          confirmText: '去授权',
          success: function (res) {
            if (res.confirm) {
              wx.openSetting({
                success: data => {
                  if (data.authSetting['scope.userLocation']) {
                    this.getLocation();
                  } else {
                    wx.showToast({
                      title: '未授权位置信息',
                      icon: 'none'
                    });
                  }
                }
              });
            }
          }
        });
      }
    });
  },

  getLocation: function () {
    wx.getLocation({
      type: 'gcj02', // 返回可以用于 wx.openLocation 的经纬度
      success: function (res) {
        const { latitude, longitude } = res;
        console.log('当前位置:', latitude, longitude);
        this.showMap(latitude, longitude);
      }.bind(this),
      fail: err => {
        console.error('获取位置失败:', err);
      }
    });
  },

  showMap: function (latitude, longitude) {
    this.setData({
      latitude,
      longitude
    });

    // 强制更新地图组件
    this.updateMap();
  },

  updateMap: function () {
    const mapContext = wx.createMapContext('myMap');
    mapContext.moveToLocation();
  }
});

  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值