总共是 3 步,接入还是非常简单的。
1. 首先你需要登录当前小程序的账号
在控制台开发那一栏中,选择开发者工具,就能开通腾讯位置服务了。按顺序点,我记得是需要手机号。然后在设置选项中,拿到APPID
点开详情,就能修改当前开发的小程序设置了,在基本信息中将APPID填上。
这时候我们就能在小程序中使用map组件了。
2. 在app.json中添加permission
,"permission": {
"scope.userLocation": {
"desc": "你的位置信息将用于小程序位置接口的效果展示"
}
},
然后写个界面
<view class='view'>
<map longitude="{{longitude}}" latitude="{{latitude}}" markers="{{markers}}" covers="{{covers}}" show-location>
</map>
</view>
wxss
/* pages/map/map.wxss */
page {
height: 100%;
}
.view {
width: 100%;
height: 100%;
}
map {
width: 100%;
height: 100%;
background-color: #f7f7f7;
}
3. 获取用户的位置
这里先说
wx.getLocation
,这个方法是显示用户在当前map上的位置,和openLocation
不同,不需要用户手动位置信息授权,体验较好。
wx.getLocation({
type: 'gcj02',
altitude: true,
//定位成功,更新定位结果
success: function(res) {
var latitude = res.latitude
var longitude = res.longitude
var speed = res.speed
var accuracy = res.accuracy
that.setData({//赋值
longitude: longitude,
latitude: latitude,
speed: speed,
accuracy: accuracy
})
}, //定位失败回调
fail: function() {
wx.hideLoading();
console.log("getLocationFail")
},
complete: function() {
//隐藏定位中信息进度
wx.hideLoading()
}
})
4. 多个位置标记
有时候我会想实现类似摩拜单车的地图功能,打开地图,能够查看现有单车的位置。这时候需要在地图上做多个标记。
这里比较关键的一点就是marker这个参数,是可以传入数组的。官网上也有类似的Demo,这样我们想要的功能就实现了。至于定位的参数,当然是问服务器大哥们要啦。Ok,让我们开搞。
wx.showLoading({
title: '加载中',
mask: true
})
//请求所有点
wx.request({
url: 'http://192.168.14.62:8080/map.json',
data: {
},
method: "GET",
header: {
"content-type": "application/json"
},
success: function(res) {
console.log(res.data.location)
var location = res.data.location;
var mks = [];
if ("" != res.data.location || res.data.location != null) {
for (var i = 0; i < location.length; i++) {
mks.push({ //赋值数组
id: location[i].id,
latitude: location[i].latitude,
longitude: location[i].longitude,
iconPath: '../../images/anchor.png', //图标路径
width: 30,
height: 30
})
}
that.setData({
markers: mks
}), wx.hideLoading();
}
}
})
5. 点击markers图标跳转页面
一种需求,点击标志地点,跳转到详情页面。
这个需求比较简单,一般都是带参数的跳转。
这里需要注意的是 markers绑定点击事件必须给markers的id属性赋值。不然点击事件会失效。看下代码。
- 添加点击事件
bindmarkertap
<!--pages/map/map.wxml-->
<view class='view'>
<map longitude="{{longitude}}" latitude="{{latitude}}" bindmarkertap="skipToDetails" markers="{{markers}}" covers="{{covers}}" show-location>
</map>
</view>
- 跳转并传递id参数
//点击事件处理
skipToDetails: function(e) {
console.log("click" + e.markerId)
//跳转
wx.navigateTo({
url: '../record_details/record_details?id=' + e.markerId //详情
})
},
搞定。
网友评论