0

我正在尝试使用与在地图上绘制标记集合相同的坐标来绘制 lineString。绘制标记,然后 lineString 应该绘制连接标记,lineString 使用与标记相同的坐标。

不过,我遇到了奇怪的问题,有时所有线条都画了,有时只画了一条线。但通常会缺少一两行。当我在 lineString 上运行 getCoordinates() 时,它会返回与标记位置相同的所有坐标,但有些线没有绘制。

一些代码:

// location data, contains x/y coords
var locs = JSON.parse(loc_data);  
var lineCoords = [];
var lat;
var lng;

// loop through loc data and output the markers 
for (var key in locs) {
    if (locs.hasOwnProperty(key)) {

        lat = locs[key].lat;
        lng = locs[key].lng;

        // store the coords in an array to be used for the lineString
        lineCoords.push([lat,lng]);

        // create marker and add to map
        var iconFeature = new ol.Feature({
            geometry: new ol.geom.Point([lat, lng]),
        });            

        var vectorSource = new ol.source.Vector({
            features: [iconFeature]
        });

        var vectorLayer = new ol.layer.Vector({
            source: vectorSource
        });

        map.addLayer(vectorLayer);                                               
    }                
}


// draw lineString using coordinates in lineCoords array
var line = new ol.geom.LineString(lineCoords);

var layerLines = new ol.layer.Vector({
    source: new ol.source.Vector({
        features: [new ol.Feature({
                geometry: line,
                name: 'Line'
            })]
    }),
});

map.addLayer(layerLines);

上面的代码看起来很合乎逻辑,我看不出哪里有问题,就像说的那样,有时所有的线都被画了,有时只画了一条。

任何人都可以对此有所了解吗?

4

1 回答 1

0

尝试更改:

// location data, contains x/y coords
var 
    locs = JSON.parse(loc_data),
    lineCoords = [], features = [],
    lat, lng, iconFeature
;

// loop through loc data and output the markers 
for (var key in locs) {
    if (locs.hasOwnProperty(key)) {

        lat = locs[key].lat; //is this already EPSG:3857 ?
        lng = locs[key].lng;

        // store the coords in an array to be used for the lineString
        lineCoords.push([lng, lat]);

        // create marker and add to map
        iconFeature = new ol.Feature({
            geometry: new ol.geom.Point([lng, lat]),
        });
        features.push(iconFeature);
    }                
}

var
    vectorSource = new ol.source.Vector({
        features: features //your LineString could also be included here
    }),
    vectorLayer = new ol.layer.Vector({
        source: vectorSource
    }),
    // draw lineString using coordinates in lineCoords array
    line = new ol.geom.LineString(lineCoords),
    layerLines = new ol.layer.Vector({
        source: new ol.source.Vector({
            features: [new ol.Feature({
                geometry: line,
                name: 'Line'
            })]
        })
    })
;
map.addLayer(vectorLayer);
map.addLayer(layerLines);
于 2015-08-21T12:36:06.210 回答