我正在尝试使用相同的坐标绘制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);
上面的代码似乎非常符合逻辑,我无法看到它可能出现问题的地方,并且就像所说的那样,有时会绘制所有线条,有时只绘制一条线。
任何人都可以对此有所了解吗?
答案 0 :(得分: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);