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函数时,在“ vectorSource.addFeature(features)”行显示错误“未捕获的TypeError:a.addEventListener不是函数”

最佳答案

通过在addFeature的末尾添加(s)进行修复。它的addFeatures而不是addFeature。

关于javascript - json数据的openlayer vectorSource错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45695079/

10-12 15:56