Search code examples
javascriptjsonopenstreetmap

openlayer vectorSource error with json data


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 and createMarkers function has very similar codes. addFeatures function has no issues but when createMarkers function is called, it shows an error "Uncaught TypeError: a.addEventListener is not a function" at line "vectorSource.addFeature(features)"


Solution

  • fixed by adding (s) at the end of addFeature. its addFeatures instead of addFeature.