项目中在百度地图上绘制 信息窗口 的的时候需要获取后台数据进行绘制,可是用的时候用户并没有添加数据,
所以后天返回 字段 为 null,显示在页面中不太美观,然后就遇到了我要记录的问题:
地图绘制代码:
updated() { // 页面更新时调用
this.$nextTick(() => {
if (this.isReady) {
this.initMap()
}
})
},
// 地图绘制
initMap() {
/* eslint-disable */
console.log('地图初始化monInfo' + JSON.stringify(this.monInfo))
var map = new BMap.Map('allmap')
var point = new BMap.Point(this.mapInit.lng, this.mapInit.lat)
map.centerAndZoom(point, 15)
var marker = new BMap.Marker(point) // 创建标注
map.addOverlay(marker) // 将标注添加到地图中
var top_left_navigation = new BMap.NavigationControl() // 左上角,添加默认缩放平移控件
map.addControl(top_left_navigation)
map.enableScrollWheelZoom(true)
var opts = { // 定义信息窗口样式
width: 200, // 信息窗口宽度
height: 100, // 信息窗口高度
enableMessage: true // 设置允许信息窗发送短息
}
var html = ''
const json = JSON.parse(this.monInfo.realTimeData)
html += '<div>车牌:' + this.monInfo.plateNo + '</div>'
html += '<div>速度:' + json.CurrentSpeed + '</div>'
html += '<div>时间:' + this.monInfo.alarmStart + '</div>'
html += '<div>地址:' + this.monInfo.alarmAddress + '</div>'
var infoWindow = new BMap.InfoWindow(html, opts)
/* eslint-enable */
setTimeout(function() {
map.openInfoWindow(infoWindow, point) // 绘制信息窗口
}, 600)
}
有关于$nextTick 方法,详情请看这里。
如果用户并没有设置地址,那么界面会是这个样子:
不太好看,所以需要做一下处理,详细如下:
var html = ''
const json = JSON.parse(this.monInfo.realTimeData)
html += '<div>车牌:' + this.monInfo.plateNo + '</div>'
html += '<div>速度:' + json.CurrentSpeed + '</div>'
html += '<div>时间:' + this.monInfo.alarmStart + '</div>'
// 单拿地址来说,如果这样写,没有问题,但是会显示null
html += '<div>地址:' + this.monInfo.alarmAddress + '</div>'
// 我尝试这这样写
html += '<div>地址:' + this.monInfo.alarmAddress === null ? '空' :
this.monInfo.alarmAddress + '</div>' // 还是不行
// 再这样
html += '<div>地址:' + this.monInfo.alarmAddress || '' + '</div>' // 也不行
// 正确的写法应该这样
const monInfoAlarmAddress = this.monInfo.alarmAddress === null ? '空' : this.monInfo.alarmAddress
html += '<div>地址:' + monInfoAlarmAddress + '</div>'
var infoWindow = new BMap.InfoWindow(html, opts)
/* eslint-enable */
// 在页面绘制需要等待数据加载完成,所以600毫秒以后绘制
setTimeout(function() {
map.openInfoWindow(infoWindow, point)
}, 600)
使用三目运算符直接拼接,界面是这样:
为什么使用三目拼接不行呐,可能原因是三目运算符先执行,然后里面执行结果有 return,所以这样写不行
而且我也试着用Vue的 computed 计算属性来做,也是不行,这里记录一下