前言:
在使用小程序的腾讯地图时发现一个问题,map这个组件作为单独一个页面的时候是没有问题的,但是,如果作为子组件的时候,效果就出不来,而且所有的方法,比如定位,移动等都会报错失效。
目录:
对比不同:使用wx.createMapContext增加了额外的参数this
失败代码(单独组件是成功代码,作为子组件失败):
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
let self =this;
self.mapCtx = wx.createMapContext('myMap')
// 实例化API核心类
qqmapsdk = new QQMapWX({
key: 'BR7BZ-GVEKW-5UDRM-RIFXT-LXCQ5-IYBHU'
});
wx.showLoading({
title: '加载中'
});
//定位
wx.getLocation({
type: 'wgs84',
success(res) {
//console.log(res)
const latitude = res.latitude
const longitude = res.longitude
const speed = res.speed
const accuracy = res.accuracy
//你地址解析
qqmapsdk.reverseGeocoder({
location: {
latitude: latitude,
longitude: longitude
},
success: function (res) {
//console.log(res)
self.setData({
latitude: latitude,
longitude: longitude,
currentRegion: res.result.address_component,
keyword: self.data.defaultKeyword
})
// 调用接口
self.nearby_search();
},
});
},
fail(err) {
//console.log(err)
wx.hideLoading({});
wx.showToast({
title: '定位失败',
icon: 'none',
duration: 1500
})
setTimeout(function () {
wx.navigateBack({
delta: 1
})
}, 1500)
}
})
},
//监听拖动地图,拖动结束根据中心点更新页面
mapChange: function (e) {
let self = this;
if (e.type == 'end' && (e.causedBy == 'scale' || e.causedBy == 'drag')){
self.mapCtx.getCenterLocation({
success: function (res) {
//console.log(res)
self.setData({
nearList:[],
latitude: res.latitude,
longitude: res.longitude,
})
self.nearby_search();
}
})
}
},
正确代码:
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
let self =this;
self.mapCtx = wx.createMapContext('myMap',this)
// 实例化API核心类
qqmapsdk = new QQMapWX({
key: 'BR7BZ-GVEKW-5UDRM-RIFXT-LXCQ5-IYBHU'
});
wx.showLoading({
title: '加载中'
});
//定位
wx.getLocation({
type: 'wgs84',
success(res) {
//console.log(res)
const latitude = res.latitude
const longitude = res.longitude
const speed = res.speed
const accuracy = res.accuracy
//你地址解析
qqmapsdk.reverseGeocoder({
location: {
latitude: latitude,
longitude: longitude
},
success: function (res) {
//console.log(res)
self.setData({
latitude: latitude,
longitude: longitude,
currentRegion: res.result.address_component,
keyword: self.data.defaultKeyword
})
// 调用接口
self.nearby_search();
},
});
},
fail(err) {
//console.log(err)
wx.hideLoading({});
wx.showToast({
title: '定位失败',
icon: 'none',
duration: 1500
})
setTimeout(function () {
wx.navigateBack({
delta: 1
})
}, 1500)
}
})
},
//监听拖动地图,拖动结束根据中心点更新页面
mapChange: function (e) {
let self = this;
if (e.type == 'end' && (e.causedBy == 'scale' || e.causedBy == 'drag')){
self.mapCtx.getCenterLocation({
success: function (res) {
//console.log(res)
self.setData({
nearList:[],
latitude: res.latitude,
longitude: res.longitude,
})
self.nearby_search();
}
})
}
},
对比不同:使用wx.createMapContext
增加了额外的参数this
self.mapCtx = wx.createMapContext('myMap',this)
官方解释:入口
相关api文档:
MapContext wx.createMapContext(string mapId, Object this)
创建 map 上下文 MapContext 对象。
参数
string mapId
map 组件的 id
Object this
在自定义组件下,当前组件实例的this,以操作组件内 map 组件
返回值
MapContext