一、案例描述
设计一个小程序,演示 map 组件、wx.getLocation、wx.chooseLocation 和 wx.openLocation 的功能和使用方法。小程序运行后可以显示给定经纬度的地图和一些地图标识,还可以实现选择位置和打开位置的功能。
二、实现思路
- 使用 map 组件显示地图,通过 longitude、latitude 设置地图中心点,通过 markers 数组设置标记点。
- 每个标记点通过 iconPath 指定自定义图标,通过 label 设置文字标签。
- 页面下方放置两个按钮:选择位置调用 wx.chooseLocation;打开位置先 wx.getLocation 再 wx.openLocation。
- app.json 中配置 requiredPrivateInfos 和 permission.scope.userLocation。
三、核心代码
index.wxml
<mapid="my-map"longitude="{{longitude}}"latitude="{{latitude}}"markers="{{markers}}"show-location="true"/><viewclass="btnLayout"><buttontype="primary"size="mini"bind:tap="chooseLocation">选择位置</button><buttontype="primary"size="mini"bind:tap="openLocation">打开位置</button></view>index.js
Page({data:{longitude:126.660821,latitude:45.572903,markers:[{id:1,longitude:126.660821,latitude:45.572903,iconPath:'/images/loc01.png',width:28,height:28,label:{content:'我的位置',color:'#0000ff',bgColor:'#ffff00',fontSize:20}},{id:2,longitude:126.659702,latitude:45.57112,iconPath:'/images/loc02.png',width:32,height:32,label:{content:'黑龙江东方学院南门',color:'#ffff00',bgColor:'#ff00ff',fontSize:20}},{// 功能扩展:第 3 个标记点id:3,longitude:126.664502,latitude:45.5752,iconPath:'/images/loc03.png',width:36,height:36,label:{content:'第一学生公寓',color:'#ffffff',bgColor:'#0000ff',fontSize:20}}]},chooseLocation(){wx.chooseLocation({success:(res)=>{this.setData({longitude:res.longitude,latitude:res.latitude})}})},openLocation(){wx.getLocation({type:'gcj02',success:(res)=>{wx.openLocation({latitude:res.latitude,longitude:res.longitude})}})}})app.json 关键配置
{"requiredPrivateInfos":["getLocation","chooseLocation"],"permission":{"scope.userLocation":{"desc":"你的位置信息将用于小程序位置接口的效果展示"}}}四、关键知识点
- map 组件:longitude、latitude、markers、show-location。
- marker 对象:id、longitude、latitude、iconPath、width、height、label。
- 三个位置 API:wx.getLocation(type=gcj02)、wx.chooseLocation()、wx.openLocation()。
- 隐私与权限:requiredPrivateInfos 必须声明,permission.scope.userLocation.desc 为用途说明。
五、成果展示
六、总结
本案例综合使用 map 组件和三个位置 API,实现了地图显示、标记点展示、选点移动和打开内置地图导航等功能,并通过添加第 3 个 marker 完成了功能扩展。