1. 安装微信开发者工具(下载稳定版)
https://developers.weixin.qq.com/miniprogram/dev/devtools/download.html
2. 去微信小程序注册获取App id(开发管理-开发设置)
3. 获取位置信息需要设备的允许,在全局的app.json文件做一个请求获取位置信息
"permission": {
"scope.userLocation": {
"desc": "你的位置信息将用于小程序定位"
}
}
4. 在app.json中添加文件名,"pages/maps/maps",命名随意,这里命名为maps
5. 选择编译模式,切换到maps
5. 在map.js文件中,设置获取位置信息的方法
Page({
/**
* 页面的初始数据
*/
data: {
// 纬度和经度,并赋初值
latitude: 10.11,
longitude: 10.11,
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
var that = this
//获取当前的地理位置
wx.getLocation({
type: 'gcj02',
isHighAccuracy: true,
// 获取成功
success: function (res) {
//赋值经纬度
that.setData({
latitude: res.latitude,
longitude: res.longitude,
})
}
})
},
})
6. 在wxml文件中编写
<view style="width: 100%; height: 100%;">
<map longitude='{{longitude}}' latitude='{{latitude}}' style="width: 100%; height: 100%;" show-location="true"></map>
</view>
longitude和latitude是必填的,实测不填的话就给显示到北京,所以我们可以把js文件中data的数据longitude和latitude直接用就可以了
7. wxss文件
page{
height: 100%;
}
8. 这里在pc上测试定位会定位到当地政府,如果在手机端测试会定位到准确位置,不过本来做的就是手机端的,所以这个小bug可以忽略
效果图: