记录如何设置小程序多点标记,从标记点跳转到详情页面,以及中途遇到的问题;
标点数据从后台获取,先上完整的代码;
xml:
<map
id="myMap"
markers="{{markers}}"
show-location
include-points="{{markers}}"
bindmarkertap="toaddress"
bindcallouttap="toaddress"
wx:if="{{hasMarkers}}"
>
</map>
js:
//index.js
//获取应用实例
const app = getApp()
const util=require("../../utils/util.js")
Page({
/**
* 页面的初始数据
*/
data: {
token:"",
points:[],
mapCtx:"",
markers: [],
hasMarkers:false,//判断数据是否请求,标点数据请求成功后,将该参数设置为true;
mapWidth: '',
mapHeight: ''
},
onReady: function () {
},
/**
* 生命周期函数--监听页面加载
*/
onShow:function(){
this.getMap();
var sy = wx.getSystemInfoSync(),
mapWidth = sy.windowWidth *1.9,
mapHeight = sy.windowHeight *1.9;
//设置地图显示的宽高;
this.setData({
mapWidth: mapWidth,
mapHeight: mapHeight,
});
},
onLoad: function () {
},
toaddress: function (e) {
wx.navigateTo({
url: '/pages/pdetail/pdetail?id='+e.detail.markerId,
})
},
includePointsFn: function () {
// 缩放视野展示所有经纬度(小程序API提供)
let mapCtx = wx.createMapContext('myMap'); // map为地图的id
var _this=this
let point=[];
for (let i = 0; i< _this.data.markers.length;i++){
let item={
latitude: _this.data.markers[i].latitude,
longitude: _this.data.markers[i].longitude
}
point.push(item)
}
_this.setData({
points:point
})
mapCtx.includePoints({
padding: [70,50,50,50],//设置padding
points: point,
})
},
//项目地图
getMap:function(){
this.setData({
token:app.globalData.token
})
let data={
token:this.data.token,
}
util.request(app.globalData.baseUrl+'index/getMapList',data,"post").then((res)=>{
let arry=[]
for(let i=0;i<res.data.data.length;i++){
if (res.data.data[i].situation==1){
let item = {
id: res.data.data[i].id,
latitude: res.data.data[i].latitude,
longitude: res.data.data[i].longitude,
iconPath: 'images/icon-2.png',
callout: {
content: res.data.data[i].programName,
padding: 10,
display: 'ALWAYS',
textAlign: 'center',
}
}
arry.push(item);
}else{
let item = {
id: res.data.data[i].id,
latitude: res.data.data[i].latitude,
longitude: res.data.data[i].longitude,
iconPath: 'images/icon-1.png',
callout: {
content: res.data.data[i].programName,
padding: 10,
display: 'ALWAYS',
textAlign: 'center',
}
}
arry.push(item);
}
}
this.setData({
markers:arry,
hasMarkers:true
})
this.includePointsFn();
})
},
})
遇到的问题:
1:从后台获取数据后,由于一开始markers为空,导致标记点未被渲染,不显示;
解决方法:设置hasMarkers,默认值为flase,当markers数组被赋值后,将其设置为true;
2:点击callout时,不跳转详情页
解决方法:bindcallouttap="toaddress" ,将bindcallouttap事件绑定toaddress方法;
3:标记点上方的callout显示不完全;
解决办法:
设置padding
let mapCtx = wx.createMapContext('myMap'); // map为地图的id
mapCtx.includePoints({
padding: [70,50,50,50],//再安卓手机中,取第一个值
points: point,
})