Openlayers:如何删除功能?

时间:2018-05-09 09:13:27

标签: javascript openlayers-3

当用户点击地图添加指针或标记时,我尝试在Openlayers上运行脚本。我已经完成了这部分,但我在这里遇到了一些问题。

当用户点击地图时,旧指针会在那里加工,但我想删除所有指针,并尝试仅保留用户最近点击的点。

请帮我解决这个问题。 这是我的代码:[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>

1 个答案:

答案 0 :(得分:2)

在添加功能之前使用vectorSource.clear();

vectorSource.clear();
vectorSource.addFeature(feature);