Openlayers 3:每次将线段添加到 LineString 时重新绘制地图层

Openlayers 3: redrawing the map layer each time a segment is added to a LineString

跟进

我正在使用 setInterval 循环逐段动画绘制 LineString。每次循环遍历函数并添加一个片段时,我都会重新渲染图层。这是最有效的方法吗?代码有效,虽然我得到一个

AssertionError: Assertion failed: listeners already registered

第一次循环后的每个循环都出错。

相关代码如下:

    function makeLineString(multipointCoords) {

        var trackStyle = new ol.style.Style({
            stroke: new ol.style.Stroke({
                color: 'rgba(255,0,255,0.2)',
                width: 0.5
            })
        });

        var trackFeature = new ol.Feature({
            geometry: new ol.geom.LineString([
                ol.proj.transform(multipointCoords[0][0], 'EPSG:4326', 'EPSG:3857')
            ])
        });

        var trackLayer = new ol.layer.Vector({
            source: new ol.source.Vector({
                features: [trackFeature],
            }),
            style: trackStyle
        });

        var coordinate, i = 1,
            length = multipointCoords[0].length;
        var timeInterval = 250;
        console.log(i);

        var timer;
        timer = setInterval(function() {
            segmentConstruction(multipointCoords);
        }, timeInterval);

        function segmentConstruction(multipointCoords) {

            coordinate = ol.proj.transform(multipointCoords[0][i], 'EPSG:4326', 'EPSG:3857');

            trackFeature.getGeometry().appendCoordinate(coordinate);

            if (i === length-1) {
                clearInterval(timer);
            } else {
                i++;
                map.addLayer(trackLayer);
            };
        };
    };

不,不要这样做。你可能想要这样的东西:

var lineString = new ol.geom.LineString([
    ol.proj.fromLonLat(multipointCoords[0][0])
]);
var trackFeature = new ol.Feature({
    geometry: lineString
});

然后是你的追加函数:

function segmentConstruction(multipointCoords) {

    coordinate = ol.proj.fromLonLat(multipointCoords[0][i]);
    lineString.appendCoordinate(coordinate);

    if (i === length-1) {
        clearInterval(timer);
    } else {
        i++;
        //map.addLayer(trackLayer); <----- remove this
    };
};

http://jsfiddle.net/jonataswalker/ots444of/