var vectorSource = new ol.source.Vector({
projection: 'EPSG:4326'
});
var vectorLayer = new ol.layer.Vector({
source: vectorSource
});
var map = new ol.Map({
target: 'mapdiv',
renderer: 'canvas',
layers: [new ol.layer.Tile({source: new ol.source.OSM()}),vectorLayer],
view: new ol.View({
center: ol.proj.transform([2.1833, 41.3833], 'EPSG:4326', 'EPSG:3857'),
zoom: 2
})
});
var sessionData = {"4798":{"location":[{"lat":27.714622020721,"lng":85.31263589859}]},"5873":{"location":[{"lat":59.944732189178,"lng":17.821261882782}]}};
createMarkers(sessionData);//this function has issues
//this function has no issue
function addFeatures() {
var i, lat, lon, geom, feature, features = [];
for(i=0; i< 10; i++) {
lat = Math.random() * 174 - 87;
lon = Math.random() * 360 - 180;
geom = new ol.geom.Point(ol.proj.transform([lon,lat], 'EPSG:4326', 'EPSG:3857'));
feature = new ol.Feature(geom);
features.push(feature);
}
vectorSource.addFeatures(features);
}
//this function show error
function createMarkers(sessData) {
var geom, feature, features = [];
$.each(sessData,function(key,val) {
var locations = val.location;
if(location.length == 0) {
return true;
}
$.each(locations,function(index,value) {
if(value.lng == 0 || value.lat == 0) {
return;
}
geom = new ol.geom.Point(ol.proj.transform([value.lng,value.lat], 'EPSG:4326', 'EPSG:3857'));
feature = new ol.Feature(geom);
features.push(feature);
});
});
vectorSource.addFeature(features);
}
addFeatures和createMarkers函数有非常相似的代码。 addFeatures函数没有问题,但是当调用createMarkers函数时,它会显示错误&#34; Uncaught TypeError:a.addEventListener不是函数&#34; at line&#34; vectorSource.addFeature(features)&#34;
答案 0 :(得分:1)
通过在addFeature末尾添加(s)来修复。它的addFeatures而不是addFeature。
答案 1 :(得分:1)
我希望这可以帮助您...
var coords = [];
for (var i=0;i<7;i++){
var x= Math.random()*360-180;
var y= Math.random()*180-90;
coords[i]= [x,y];
} //end for
var mapCenterCoord = [-65.65, 10.10];
var lineString = new ol.geom.LineString(coords);
lineString.transform('EPSG:4326', 'EPSG:3857');
var feature = new ol.Feature({
geometry: lineString,
name: 'Line'
});
var lineStyle = new ol.style.Style({
stroke: new ol.style.Stroke({
color: '#0080FF',
width: 3
})
});
var source = new ol.source.Vector({
features: [feature]
});
var vector = new ol.layer.Vector({
source: source,
style: [lineStyle]
});
var map = new ol.Map({
target: 'map',
layers: [new ol.layer.Tile({ source: new ol.source.OSM() }), vector],
view: new ol.View({ center: mapCenterCoord, zoom: 3 })
});
致谢。
J。