Search code examples
openlayers-6

Remove all markers from Openlayers map before adding new


I render a map with this code

var jsonData = '';
let userData = null;
var iconFeatures = [];
var source = new ol.source.Vector();

function getMap(facilities = "") {
    console.log(facilities);

    $.ajax({
        url : "getMarkers.php",
        type: "POST",
        cache: false,
        data:{
                facility:facilities
            },
        success:function(result){
            //clusters.clear();
            console.log(result);
            var stringified = JSON.stringify(result);
            jsonData = JSON.parse(stringified);
            $(".debug").text(stringified);
            console.log(Object.keys(result).length);   
            setIconFeatures();
            source.addFeatures(iconFeatures);
            
        },
    });

}

function createStyle(src, img) {
    return new ol.style.Style({
        image: new ol.style.Icon(({
            anchor: [0.5, 0.96],
            crossOrigin: 'anonymous',
            src: src,
            img: img,
            imgSize: img ? [img.width, img.height] : undefined
        }))
    });
}

function setIconFeatures() {
    for(var key in jsonData) {          
        var jsonItem = jsonData[key];
    
        var iconFeature = new ol.Feature(new ol.geom.Point(ol.proj.fromLonLat([jsonItem.long, jsonItem.lat])));
        iconFeature.setId(key);
        iconFeature.set('style', createStyle('http://test.brugminbaghave.dk/img/BMB-marker.png', undefined));
        iconFeatures.push(iconFeature);
    }
}

var distance = document.getElementById('distance');

var unclusteredLayer = new ol.layer.Vector({
    source: source,
    style: function(feature) {
        return feature.get('style');
    },
    maxResolution: 300
});

var clusterSource = new ol.source.Cluster({
    distance: parseInt(40, 10),
    source: source
});

var styleCache = {};

var clusters = new ol.layer.Vector({
    source: clusterSource,
    style: function(feature) {
        var size = feature.get('features').length;
        var style = styleCache[size];
        if (!style) {
            style = new ol.style.Style({
                image: new ol.style.Circle({
                    radius: 12,
                    stroke: new ol.style.Stroke({
                        color: '#fff'
                    }),
                    fill: new ol.style.Fill({
                        color: '#158D30'
                    })
                }),
                text: new ol.style.Text({
                    text: size.toString(),
                    fill: new ol.style.Fill({
                        color: '#fff'
                    })
                })
            });
            styleCache[size] = style;
        }
        return style;
    },
    minResolution: 301
});

var raster = new ol.layer.Tile({
    source: new ol.source.OSM()
});

var map = new ol.Map({
    target: 'map',
    layers: [raster, clusters, unclusteredLayer],
    view: new ol.View({
        center: ol.proj.fromLonLat([9.9191, 56.0227]),
        zoom: 7
    })
});

getMap();

Underbeath my map I have som checkboxes. When I check one of those I call getMap() and the getMarkers.php delivers new markers. But how do I remove old markers before adding the new ones? As it is now, I jus add the new markers to the map.

I have tried with something like source.clear() or similar, but I can't hit the right combination.

What should I look for?


Solution

  • You will need source.clear(). You also need to clear the iconFeatures array before pushing new features to it, otherwise you will also add back the old features

            iconFeatures = [];
            setIconFeatures();
            source.clear();
            source.addFeatures(iconFeatures);