addFeature和removeFeature

添加小图标到地图上,并移除上一次添加到地图上的小图标

// 点击事件
rowClick(row){
    // 1. 设置地图中心点和缩放级别
    let center = [row.longitude, row.latitude];
    let zoom = 18;
    let view = this.map.getView();
    view.setCenter(center);
    view.setZoom(zoom);

    // 2. 显示当前选择的某一行显示在地图上
    this.addSelectedToMap(row);

    // 3. 清除上一次选择某一行之后出现在地图上的小图标
    this.clearOldIconFeature();
},

addSelectedToMap(row){
    let createLabelStyle1 = function (feature) {
        return new Style({
            image: new Icon(
                ({
                    anchorOrigin: 'top-right',  //图标起点
                    anchorXUnits: 'fraction',   //指定x值为图标点的x值
                    anchorYUnits: 'pixels',     //指定Y值为像素的值
                    offsetOrigin: 'top-right',  //偏移
                    opacity: 1,              //透明度
                    src: '/img/demo.png'      //图标的url
                })),
        });
    };
    let wgsLngLat = [row["longitude"], row["latitude"]];
    let iconFeature = new Feature({
        geometry: new Point(wgsLngLat)
    });
    iconFeature.setStyle(createLabelStyle1(iconFeature));
    this.vectorSource.addFeature(iconFeature);    // 添加iconFeature到地图上
    this.iconFeature = iconFeature;        // 保留添加到map上的iconFeature,等待删除
    this.map.addOverlay(this.overlay);
},

clearOldIconFeature(){
    if(this.iconFeature !== null){
        // listens to the 'addfeature' event once and then removes the preIconFeature.
        this.vectorSource.once('addfeature', (event) => {
            const feature = event.feature;
            this.vectorSource.removeFeature(this.iconFeature);    // 删除上一个iconFeature
        });
    }
},