Ad

Openlayers: How Can I Remove A Feature?

- 1 answer

I'm trying to run a script base on the Openlayers when a user clicks on a map add a pointer or marker. I've already done this part but I have a little problem here.

when users click on the map the older pointers will steel there but I want to delete all pointer and try to keep just the recently clicked point by the user.

Please help me with this problem. and here is my code: [openlayers 3]

<script>
    var
        vectorSource = new ol.source.Vector(),
        vectorLayer = new ol.layer.Vector({
            source: vectorSource
        }),
        olView = new ol.View({
            center: ol.proj.fromLonLat([48.4831, 36.6681]),
            zoom: 8,
            minZoom: 2,
            maxZoom: 20
        }),
        map = new ol.Map({
            target: document.getElementById('map'),
            view: olView,
            layers: [
                new ol.layer.Tile({
                    style: 'Aerial',
                    source: new ol.source.OSM()
                }),
                vectorLayer
            ]
        })
        ;

    var iconStyle = new ol.style.Style({
        image: new ol.style.Icon({
            anchor: [0.5, 46],
            anchorXUnits: 'fraction',
            anchorYUnits: 'pixels',
            opacity: 0.75,
            src: 'https://openlayers.org/en/v3.8.2/examples/data/icon.png'
        }),
        text: new ol.style.Text({
            font: '12px Calibri,sans-serif',
            fill: new ol.style.Fill({ color: '#000' }),
            stroke: new ol.style.Stroke({
                color: '#fff', width: 2
            }),
            text: 'Some text'
        })
    });
    map.on('click', function(evt){
        var feature = new ol.Feature(
            new ol.geom.Point(evt.coordinate)
        );

        var lon = ol.proj.toLonLat(evt.coordinate)[0];
        var lat = ol.proj.toLonLat(evt.coordinate)[1];

        console.info('longitude is: ' + lon + 'latitude is: ' + lat);

        feature.setStyle(iconStyle);
        vectorSource.addFeature(feature);
    });

</script>
Ad

Answer

Use vectorSource.clear(); before adding the feature:

vectorSource.clear();
vectorSource.addFeature(feature);
Ad
source: stackoverflow.com
Ad