javascript - 开放层 : How can I remove a feature?

标签 javascript openlayers-3

当用户单击 map 添加指针或标记时,我尝试运行基于 Openlayers 的脚本。我已经完成了这部分,但这里有一个小问题。

当用户单击 map 时,旧指针将指向那里,但我想删除所有指针并尝试仅保留用户最近单击的点。

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

最佳答案

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

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

关于javascript - 开放层 : How can I remove a feature?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50249636/

相关文章:

javascript - 将 Python 变量分配给 JavaScript 变量

javascript - 仅当选择一行时才显示一些 html

openlayers-3 - 在 OpenLayers 3 中的 map 旋转期间旋转要素

javascript - openlayers 3 - 加载具有最高缩放级别图 block 的 TileLayer,但以所有缩放级别显示

javascript - OL3 - 检测功能点击时出现问题

javascript - 将数组添加到数组项中

javascript - 如何使用 kendo ui 网格从带有模板选项的 javascript onclick 传递硬编码字符串值?

javascript - HTML 复选框返回值?

javascript - 打开第 3 层标签不会显示

openlayers-3 - ol3/Openlayers3 : change radius of circle when zoomed