i am trying to draw a lineString using the same coordinates that are used to draw a collection of markers on a map. The markers are drawn, then the lineString should draw joining the markers, the lineString uses the same coords as the markers.
I am having strange issues though, sometimes all the lines draw, sometimes only one of the lines draw. but usually there will be one or two lines missing. when i run getCoordinates() on the lineString, it returns me all the same coordinates as the marker locations, yet some of the lines are not drawn.
some code:
// 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);
the code above seems pretty logical, i can't see where there could be a problem with it, and like is said, sometimes all lines are drawn and sometimes only one is drawn.
can anyone shine some light on this?
Try with the changes:
// 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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.