微信小程序 Map 组件使用指南

2026-01-08前端6 分钟633 次阅读
AI 摘要salmon-ai

本文详细解析了微信小程序原生 Map 组件的使用方法,介绍了地图展示、标记点、轨迹线、实时位置追踪和 MapContext 控制等核心能力,并明确区分了哪些功能可免费使用、

微信小程序 Map 组件使用指南

一、Map 组件简介

微信小程序提供了原生的 map 组件,支持地图展示、标记点、路线绑定、运动轨迹等功能。相比第三方地图 SDK,原生组件性能更好,且无需额外引入依赖。

重要提示:小程序原生 map 组件的 polyline(轨迹线)功能是完全免费的,不需要申请任何 API Key,非常适合个人开发者使用!

官方文档:https://developers.weixin.qq.com/miniprogram/dev/component/map.html

地图 API 文档:https://developers.weixin.qq.com/miniprogram/dev/api/media/map/wx.createMapContext.html

二、免费 vs 付费功能说明

功能 是否免费 说明
地图展示 ✅ 免费 基础地图渲染
markers 标记点 ✅ 免费 自定义标记点
polyline 轨迹线 ✅ 免费 绘制运动轨迹
callout 气泡 ✅ 免费 标记点气泡提示
获取用户位置 ✅ 免费 wx.getLocation
实时位置追踪 ✅ 免费 wx.startLocationUpdate
路线规划 ❌ 付费 需要腾讯位置服务 API
地点搜索 ❌ 付费 需要腾讯位置服务 API
逆地理编码 ❌ 付费 坐标转地址需要 API

结论:绘制遛狗轨迹只需要用到免费功能!

三、前置配置

1、申请地图 Key(可选)

如果只是绘制轨迹和标记点,不需要申请 Key!

只有使用以下高级功能才需要申请腾讯位置服务 Key:

  • 路线规划(驾车/步行/骑行导航)
  • 地点搜索/关键词搜索
  • 逆地理编码(坐标转地址)

如需申请:

  1. 访问腾讯位置服务:https://lbs.qq.com/
  2. 注册/登录账号
  3. 进入控制台 -> 应用管理 -> 创建应用
  4. 添加 Key,选择「微信小程序」类型
  5. 填写小程序 AppID

2、配置 app.json 权限

json 复制代码
{
  "permission": {
    "scope.userLocation": {
      "desc": "用于显示您的当前位置和记录运动轨迹"
    },
    "scope.userLocationBackground": {
      "desc": "用于后台持续记录运动轨迹"
    }
  },
  "requiredPrivateInfos": [
    "getLocation",
    "startLocationUpdate",
    "startLocationUpdateBackground"
  ],
  "requiredBackgroundModes": ["location"]
}

3、配置隐私协议

在小程序后台 -> 设置 -> 服务内容声明 -> 用户隐私保护指引中,添加「位置信息」相关说明。

三、基础使用

1、页面结构 (demo.wxml)

html 复制代码
<view class="container">
  <map 
    id="myMap"
    longitude="{{center.longitude}}"
    latitude="{{center.latitude}}"
    scale="{{scale}}"
    markers="{{markers}}"
    polyline="{{polyline}}"
    show-location="{{true}}"
    enable-zoom="{{true}}"
    enable-scroll="{{true}}"
    bindmarkertap="onMarkerTap"
    bindregionchange="onRegionChange"
    style="width: 100%; height: 100%;">
  </map>
</view>

2、页面样式 (demo.wxss)

css 复制代码
.container {
  width: 100%;
  height: 100vh;
}

3、页面逻辑 (demo.js)

javascript 复制代码
Page({
  data: {
    // 地图中心点
    center: {
      longitude: 113.9442,
      latitude: 22.5329
    },
    scale: 14, // 缩放级别 3-20
    markers: [],
    polyline: []
  },

  onLoad() {
    this.initMarkers();
    this.initPolyline();
  },

  // 初始化标记点
  initMarkers() {
    const markers = [
      {
        id: 1,
        longitude: 113.9442,
        latitude: 22.5329,
        title: '起点',
        iconPath: '/images/marker-start.png', // 自定义图标
        width: 30,
        height: 30,
        callout: {
          content: '出发点 - 南山区',
          color: '#333',
          fontSize: 12,
          borderRadius: 8,
          bgColor: '#fff',
          padding: 8,
          display: 'ALWAYS' // BYCLICK 点击显示
        }
      },
      {
        id: 2,
        longitude: 113.9612,
        latitude: 22.5429,
        title: '终点',
        iconPath: '/images/marker-end.png',
        width: 30,
        height: 30,
        callout: {
          content: '终点 - 福田区',
          color: '#333',
          fontSize: 12,
          borderRadius: 8,
          bgColor: '#fff',
          padding: 8,
          display: 'ALWAYS'
        }
      }
    ];
    this.setData({ markers });
  },

  // 初始化运动轨迹
  initPolyline() {
    const polyline = [{
      points: [
        { longitude: 113.9442, latitude: 22.5329 },
        { longitude: 113.9480, latitude: 22.5350 },
        { longitude: 113.9520, latitude: 22.5380 },
        { longitude: 113.9560, latitude: 22.5400 },
        { longitude: 113.9612, latitude: 22.5429 }
      ],
      color: '#FF5722',
      width: 4,
      dottedLine: false,
      arrowLine: true, // 显示箭头
      borderColor: '#fff',
      borderWidth: 1
    }];
    this.setData({ polyline });
  },

  // 点击标记点
  onMarkerTap(e) {
    const markerId = e.markerId;
    const marker = this.data.markers.find(m => m.id === markerId);
    if (marker) {
      wx.showToast({
        title: marker.title,
        icon: 'none'
      });
    }
  },

  // 地图视野变化
  onRegionChange(e) {
    if (e.type === 'end') {
      console.log('地图移动结束', e.detail);
    }
  }
});

三、运动轨迹动画

实现轨迹动态绘制效果

javascript 复制代码
Page({
  data: {
    center: { longitude: 113.9442, latitude: 22.5329 },
    scale: 14,
    markers: [],
    polyline: []
  },

  // 完整轨迹点数据
  fullTrackPoints: [
    { longitude: 113.9442, latitude: 22.5329 },
    { longitude: 113.9450, latitude: 22.5335 },
    { longitude: 113.9460, latitude: 22.5345 },
    { longitude: 113.9475, latitude: 22.5360 },
    { longitude: 113.9490, latitude: 22.5375 },
    { longitude: 113.9510, latitude: 22.5390 },
    { longitude: 113.9530, latitude: 22.5405 },
    { longitude: 113.9550, latitude: 22.5415 },
    { longitude: 113.9580, latitude: 22.5420 },
    { longitude: 113.9612, latitude: 22.5429 }
  ],

  onLoad() {
    this.animateTrack();
  },

  // 动画绘制轨迹
  animateTrack() {
    let index = 0;
    const points = this.fullTrackPoints;
    
    const timer = setInterval(() => {
      if (index >= points.length) {
        clearInterval(timer);
        return;
      }

      const currentPoints = points.slice(0, index + 1);
      const currentPoint = points[index];

      this.setData({
        polyline: [{
          points: currentPoints,
          color: '#07c160',
          width: 5,
          arrowLine: true
        }],
        markers: [{
          id: 1,
          longitude: currentPoint.longitude,
          latitude: currentPoint.latitude,
          iconPath: '/images/location.png',
          width: 24,
          height: 24
        }]
      });

      index++;
    }, 300); // 每300ms绘制一个点
  }
});

四、获取用户实时位置

记录用户运动轨迹

javascript 复制代码
Page({
  data: {
    center: { longitude: 0, latitude: 0 },
    scale: 16,
    markers: [],
    polyline: []
  },

  trackPoints: [], // 存储轨迹点

  onLoad() {
    this.getCurrentLocation();
  },

  // 获取当前位置
  getCurrentLocation() {
    wx.getLocation({
      type: 'gcj02',
      success: (res) => {
        this.setData({
          center: {
            longitude: res.longitude,
            latitude: res.latitude
          }
        });
        // 开始记录轨迹
        this.startTracking();
      },
      fail: () => {
        wx.showToast({ title: '获取位置失败', icon: 'none' });
      }
    });
  },

  // 开始追踪位置
  startTracking() {
    // 需要在 app.json 中配置 "requiredBackgroundModes": ["location"]
    wx.startLocationUpdate({
      success: () => {
        wx.onLocationChange(this.onLocationChange);
      }
    });
  },

  // 位置变化回调
  onLocationChange(res) {
    const point = {
      longitude: res.longitude,
      latitude: res.latitude
    };

    this.trackPoints.push(point);

    this.setData({
      center: point,
      markers: [{
        id: 1,
        longitude: point.longitude,
        latitude: point.latitude,
        iconPath: '/images/location.png',
        width: 24,
        height: 24
      }],
      polyline: [{
        points: this.trackPoints,
        color: '#FF5722',
        width: 4,
        arrowLine: true
      }]
    });
  },

  // 停止追踪
  stopTracking() {
    wx.stopLocationUpdate();
    wx.offLocationChange(this.onLocationChange);
  },

  onUnload() {
    this.stopTracking();
  }
});

五、常用属性说明

属性 类型 说明
longitude Number 中心经度
latitude Number 中心纬度
scale Number 缩放级别 3-20
markers Array 标记点数组
polyline Array 路线数组
show-location Boolean 显示当前位置
enable-zoom Boolean 允许缩放
enable-scroll Boolean 允许拖动

六、MapContext API

通过 wx.createMapContext 可以获取地图上下文,实现更多控制功能:

javascript 复制代码
Page({
  onReady() {
    // 获取地图上下文
    this.mapCtx = wx.createMapContext('myMap');
  },

  // 移动到指定位置
  moveToLocation(longitude, latitude) {
    this.mapCtx.moveToLocation({
      longitude,
      latitude
    });
  },

  // 获取当前地图中心
  getCenterLocation() {
    this.mapCtx.getCenterLocation({
      success: (res) => {
        console.log('中心点:', res.longitude, res.latitude);
      }
    });
  },

  // 缩放到包含所有标记点
  includePoints(points) {
    this.mapCtx.includePoints({
      points: points,
      padding: [50, 50, 50, 50]
    });
  },

  // 获取地图缩放级别
  getScale() {
    this.mapCtx.getScale({
      success: (res) => {
        console.log('当前缩放级别:', res.scale);
      }
    });
  }
});

七、注意事项

  1. 权限配置:需要在 app.json 中配置位置权限
json 复制代码
{
  "permission": {
    "scope.userLocation": {
      "desc": "用于记录运动轨迹"
    }
  },
  "requiredBackgroundModes": ["location"]
}
  1. 坐标系:小程序使用 gcj02 坐标系(国测局坐标),如果使用 GPS 原始坐标(wgs84)需要转换

  2. 性能优化:

    • 轨迹点过多时,进行抽稀处理(Douglas-Peucker 算法)
    • 避免频繁 setData 更新 markers/polyline
    • 使用 include-points 代替手动计算缩放级别
  3. 自定义图标:marker 的 iconPath 需要使用本地图片路径,不支持网络图片

  4. 层级问题:map 是原生组件,层级最高,使用 cover-view / cover-image 覆盖

  5. 真机调试:地图功能建议在真机上测试,模拟器可能有差异

八、常见问题

Q1: 地图不显示?

  • 检查是否设置了宽高
  • 检查经纬度是否正确(经度 -180~180,纬度 -90~90)

Q2: 获取位置失败?

  • 检查权限配置
  • 检查用户是否授权
  • iOS 需要在「设置」中开启位置权限

Q3: 标记点不显示?

  • 检查 iconPath 路径是否正确
  • 检查 width/height 是否设置
  • 检查 id 是否唯一

九、完整遛狗轨迹示例(免费方案)

以下是一个完整的遛狗轨迹记录和展示示例,全部使用免费功能实现:

1、页面结构 (walk.wxml)

html 复制代码
<view class="container">
  <!-- 遛狗统计 -->
  <view class="walk-stats">
    <view class="stat-item">
      <text class="stat-value">{{walkStats.distance}}</text>
      <text class="stat-unit">米</text>
      <text class="stat-label">总距离</text>
    </view>
    <view class="stat-item">
      <text class="stat-value">{{walkStats.duration}}</text>
      <text class="stat-unit">分钟</text>
      <text class="stat-label">时长</text>
    </view>
    <view class="stat-item">
      <text class="stat-value">{{walkStats.avgSpeed}}</text>
      <text class="stat-unit">km/h</text>
      <text class="stat-label">平均速度</text>
    </view>
  </view>

  <!-- 轨迹地图 -->
  <view class="map-container">
    <map 
      id="walkMap"
      longitude="{{center.longitude}}"
      latitude="{{center.latitude}}"
      scale="16"
      markers="{{markers}}"
      polyline="{{polyline}}"
      show-location="{{false}}"
      enable-zoom="{{true}}"
      enable-scroll="{{true}}"
      style="width: 100%; height: 100%;">
    </map>
  </view>

  <!-- 图例 -->
  <view class="legend">
    <view class="legend-item">
      <view class="legend-line"></view>
      <text>遛狗轨迹</text>
    </view>
    <view class="legend-item">
      <view class="legend-dot start"></view>
      <text>起点</text>
    </view>
    <view class="legend-item">
      <view class="legend-dot end"></view>
      <text>终点</text>
    </view>
  </view>
</view>

2、页面样式 (walk.wxss)

css 复制代码
.container {
  padding: 20rpx;
}

.walk-stats {
  display: flex;
  justify-content: space-around;
  padding: 30rpx;
  background: linear-gradient(135deg, rgba(255, 149, 0, 0.1), rgba(255, 204, 0, 0.1));
  border-radius: 16rpx;
  margin-bottom: 20rpx;
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.stat-value {
  font-size: 44rpx;
  font-weight: 700;
  color: #FF9500;
}

.stat-unit {
  font-size: 22rpx;
  color: #999;
}

.stat-label {
  font-size: 24rpx;
  color: #666;
  margin-top: 8rpx;
}

.map-container {
  width: 100%;
  height: 500rpx;
  border-radius: 16rpx;
  overflow: hidden;
}

.legend {
  display: flex;
  justify-content: center;
  gap: 40rpx;
  padding: 20rpx 0;
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 10rpx;
  font-size: 24rpx;
  color: #666;
}

.legend-line {
  width: 40rpx;
  height: 6rpx;
  background: #FF5722;
  border-radius: 3rpx;
}

.legend-dot {
  width: 16rpx;
  height: 16rpx;
  border-radius: 50%;
}

.legend-dot.start {
  background: #34C759;
}

.legend-dot.end {
  background: #FF3B30;
}

3、页面逻辑 (walk.js)

javascript 复制代码
Page({
  data: {
    center: { longitude: 113.9448, latitude: 22.5328 },
    markers: [],
    polyline: [],
    walkStats: {
      distance: 0,
      duration: 0,
      avgSpeed: 0
    }
  },

  onLoad() {
    this.loadWalkTrack();
  },

  // 加载遛狗轨迹数据
  loadWalkTrack() {
    // 模拟轨迹点数据(实际应从后端获取或本地存储读取)
    const trackPoints = [
      { longitude: 113.9430, latitude: 22.5320 },
      { longitude: 113.9435, latitude: 22.5325 },
      { longitude: 113.9442, latitude: 22.5329 },
      { longitude: 113.9448, latitude: 22.5335 },
      { longitude: 113.9455, latitude: 22.5340 },
      { longitude: 113.9460, latitude: 22.5338 },
      { longitude: 113.9465, latitude: 22.5332 },
      { longitude: 113.9462, latitude: 22.5325 },
      { longitude: 113.9455, latitude: 22.5320 },
      { longitude: 113.9448, latitude: 22.5318 },
      { longitude: 113.9440, latitude: 22.5315 },
      { longitude: 113.9432, latitude: 22.5318 },
      { longitude: 113.9430, latitude: 22.5320 }
    ];

    // 计算统计数据
    const distance = this.calculateDistance(trackPoints);
    const duration = 32; // 实际应记录开始和结束时间
    const avgSpeed = ((distance / 1000) / (duration / 60)).toFixed(1);

    // 计算中心点
    const center = {
      longitude: trackPoints.reduce((sum, p) => sum + p.longitude, 0) / trackPoints.length,
      latitude: trackPoints.reduce((sum, p) => sum + p.latitude, 0) / trackPoints.length
    };

    // 轨迹线配置(免费功能)
    const polyline = [{
      points: trackPoints,
      color: '#FF5722',      // 轨迹颜色
      width: 6,              // 线宽
      dottedLine: false,     // 是否虚线
      arrowLine: true,       // 显示箭头方向
      borderColor: '#fff',   // 边框颜色
      borderWidth: 2         // 边框宽度
    }];

    // 起点和终点标记(免费功能)
    const markers = [
      {
        id: 1,
        longitude: trackPoints[0].longitude,
        latitude: trackPoints[0].latitude,
        width: 32,
        height: 32,
        callout: {
          content: '起点',
          color: '#fff',
          fontSize: 12,
          borderRadius: 8,
          bgColor: '#34C759',
          padding: 6,
          display: 'ALWAYS'
        }
      },
      {
        id: 2,
        longitude: trackPoints[trackPoints.length - 2].longitude,
        latitude: trackPoints[trackPoints.length - 2].latitude,
        width: 32,
        height: 32,
        callout: {
          content: '终点',
          color: '#fff',
          fontSize: 12,
          borderRadius: 8,
          bgColor: '#FF3B30',
          padding: 6,
          display: 'ALWAYS'
        }
      }
    ];

    this.setData({
      center,
      polyline,
      markers,
      walkStats: {
        distance: Math.round(distance),
        duration,
        avgSpeed
      }
    });
  },

  // 计算轨迹总距离(米)- Haversine 公式(免费算法)
  calculateDistance(points) {
    let total = 0;
    for (let i = 0; i < points.length - 1; i++) {
      total += this.getDistanceBetweenPoints(points[i], points[i + 1]);
    }
    return total;
  },

  // 计算两点间距离(米)
  getDistanceBetweenPoints(p1, p2) {
    const R = 6371000; // 地球半径(米)
    const rad = Math.PI / 180;
    const lat1 = p1.latitude * rad;
    const lat2 = p2.latitude * rad;
    const deltaLat = (p2.latitude - p1.latitude) * rad;
    const deltaLng = (p2.longitude - p1.longitude) * rad;

    const a = Math.sin(deltaLat / 2) * Math.sin(deltaLat / 2) +
              Math.cos(lat1) * Math.cos(lat2) *
              Math.sin(deltaLng / 2) * Math.sin(deltaLng / 2);
    const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));

    return R * c;
  }
});

4、关键点说明

  1. polyline 属性:小程序原生支持,完全免费

    • points: 轨迹点数组
    • color: 轨迹颜色
    • width: 线宽
    • arrowLine: 显示方向箭头
  2. 距离计算:使用 Haversine 公式本地计算,不需要调用任何 API

  3. 标记点 callout:使用 callout 显示起点/终点气泡,免费功能

  4. 数据存储:轨迹点可以存储在本地(wx.setStorage)或自己的后端服务器

十、效果预览

地图标记和轨迹效果如下图所示:

十一、总结

对于个人开发者来说,小程序原生 map 组件已经能满足大部分需求:

需求 实现方式 费用
显示地图 map 组件 免费
标记打卡点 markers 属性 免费
绘制运动轨迹 polyline 属性 免费
计算轨迹距离 Haversine 公式 免费
记录用户位置 wx.getLocation 免费
实时追踪位置 wx.startLocationUpdate 免费

只有需要路线规划、地点搜索等高级功能时,才需要申请腾讯位置服务 API(有免费额度)。

觉得有用就点个赞,不用登录也能读

评论

0 条
登录 之后才能评论
—
还没有评论,来说第一句