微信小程序map组件在绑定bindregionchange事件之后,当地图视野发生改变的时候,里面的逻辑就是当地图的中心位置发生变化,通过拖拽或者放大缩小地图,通过getCenterLocation()重新获取地图的中心位置的经纬度,再去重新标记地图的markers,这个时候会导致地图上的markers图标不断的闪烁。
以下是出现图标闪烁的代码
// 拖拽地图
regionchange(e) {
if (e.type == "end") {
console.log("拖拽地图end===============", e.type);
this.refreshMap();
} else {
console.log("拖拽地图begin===============", e.type);
this.setData({
"markers[0].callout.content": "拖动中..."
});
}
},
// 刷新地图中心位置
refreshMap() {
let mapCtx = wx.createMapContext("map");
mapCtx.getCenterLocation({
success: (res) => {
// console.log("------刷新地图中心位置---------",res);
let longitude = res.longitude.toFixed(6);
let latitude = res.latitude.toFixed(6);
this.setData({
longitude: longitude,
latitude: latitude,
"markers[0].latitude": latitude,
"markers[0].longitude": longitude,
});
}
});
}
解决的方法,就是判断一下地图刷新之后的中心位置的经纬度和原来位置的经纬是否一样,再结合计算一下两点之间的距离getDistance(),改为以下的方案
// 拖拽地图
regionchange(e) {
if (e.type == "end") {
console.log("拖拽地图end===============", e.type);
this.refreshMap();
} else {
console.log("拖拽地图begin===============", e.type);
this.setData({
"markers[0].callout.content": "拖动中..."
});
}
},
// 刷新地图中心位置
refreshMap() {
let mapCtx = wx.createMapContext("map");
mapCtx.getCenterLocation({
success: (res) => {
// console.log("------刷新地图中心位置---------",res);
let longitude = res.longitude.toFixed(6);
let latitude = res.latitude.toFixed(6);
let distance = this.getDistance(latitude, longitude, this.data.latitude, this.data.longitude);
if ((latitude == this.data.latitude && longitude == this.data.longitude) || distance < 1) {
this.setData({
"markers[0].callout.content": "出发地"
});
return;
}
this.setData({
longitude: longitude,
latitude: latitude,
"markers[0].latitude": latitude,
"markers[0].longitude": longitude,
});
}
});
},
// 计算两坐标距离
getDistance: function (lat1, lng1, lat2, lng2) {
// console.log("--------getDistance--------------");
lat1 = lat1 || 0;
lng1 = lng1 || 0;
lat2 = lat2 || 0;
lng2 = lng2 || 0;
var rad1 = lat1 * Math.PI / 180.0;
var rad2 = lat2 * Math.PI / 180.0;
var a = rad1 - rad2;
var b = lng1 * Math.PI / 180.0 - lng2 * Math.PI / 180.0;
var r = 6378137;
return (r * 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(rad1) * Math.cos(rad2) * Math.pow(Math.sin(b / 2), 2)))).toFixed(0);
}
这样就可以解决了!希望可以帮到掘友萌