如何在地图中动态添加点元素,并动态加载数据
① 循环获取数据
mounted() {
this.mapT();
this.drowMap();
this.clickOnMap();
this.addOverlay();
this.addOverlay_Line();
this.mousePosition();
this.mapDianClick();
// 循环获取数据
this.alarmPointsState = setInterval(()=>{
this.getAlarmPointsData();
},3000)
},
getAlarmPointsData(){
let that = this;
Api.getGisData().then(res=>{
this.mapData2 = {};
this.basicPoints2 = [];
this.alarmPoints = [];
this.alarmFeatures = [];
// 重新构建时清除叠加层
this.map.getOverlays().getArray().slice(0).forEach(function(overlay) {
if (overlay.id != undefined) {
that.map.removeOverlay(overlay);
}
})
this.mapData2 = JSON.parse(res.Data);
this.basicPoints2 = this.mapData2.Gislnglats;
for (let i = 0; i < this.basicPoints2.length; i++) {
if (this.basicPoints2[i].Type == 3) {
this.alarmPoints.push(this.basicPoints2[i]);
}
}
})
},
② 监听数据的变化
利用计算属性来监听我们所需要的点数据alarmPoints的变化
computed: {
watchObj(){
let {alarmPoints} = this;
return {alarmPoints}
},
},
现在数据是动态的了,那么如何去实时的创建我们需要的点呢
③ 实时构建点元素
setFeature(){
// 循环数据
for (let i = 0; i < this.alarmPoints.length; i++) {
// 设置坐标
let position = [this.alarmPoints[i].Longitude, this.alarmPoints[i].Latitude];
// 构建点元素
this.alarmFeaturePoint = new Feature({geometry: new Point(fromLonLat(position))});
// 设置点样式
let style = new Style({
image: new Icon({
anchor: [0.5, 0.5], // 锚点
opacity: 1,
scale: 1,
src: 'img/icon2/gzd.png',
}),
})
this.alarmFeaturePoint.setStyle(style);
this.alarmFeatures.push(this.alarmFeaturePoint);
// 创建涟漪的动态效果
var point_div = document.createElement('div');
point_div.className = "css_animationz";
this.point_overlay = new Overlay({
element: point_div,
positioning: 'center-center',
id: '111'
});
// 将此效果通过叠加层去展示
this.point_overlay.setPosition(fromLonLat([
this.alarmPoints[i].Longitude, this.alarmPoints[i].Latitude
]))
this.map.addOverlay(this.point_overlay);
}
this.newsource.addFeatures(this.alarmFeatures);
},
// 涟漪效果的css样式
.css_animationz{
height: 30px;
width: 30px;
border-radius: 25px;
background: rgba(255, 0, 0, 0.9);
transform: scale(0);
animation: myfirst 2s;
animation-iteration-count: infinite;
}
@keyframes myfirst{
to{
transform: scale(3);
background: rgba(0, 0, 0, 0);
}
}
到这里我们动态创建的点就完成了,我们只需要将点加载进图层中就可以了,我们将创建图层写到另一个方法中,通过监听数据来构建
④ 构建图层
mapDianClick(){
//矢量标注的数据源
this.newsource = new VectorSource();
//矢量标注图层
this.newlayer = new VectorLayer({
source:this.newsource,
zIndex: 1
});
this.map.addLayer(this.newlayer);
this.setFeature();
},
⑤ 清除图层
在循环构建点元素的时候,我们每构建一个点,在下次重新构建的时候需要清除掉之前的所有点,才能重新渲染,这就需要在进入构建方法前清除掉之前的图层与叠加层
所以我们需要一个清除的方法
claerMap(){
// this.map.getOverlays().clear(); // 清除掉地图中所有的叠加层
this.map.removeLayer(this.newlayer); // 清除地图中的图层
},
如果有多个叠加层,则可以在进入构建点方法时去清除叠加层,在此方法中清除会使所有叠加层失效
将此方法在监听数据时调用
watch: {
watchObj: {
handler() {
this.claerMap();
this.mapDianClick();
},
deep: true,
},
到这里我们就完成了动态数据实时加载点的效果