[GIS] Getting extent of vector source in OpenLayers

openlayers

I create features from data projected in UTM32 and set up the projection accordingly as shown below. My problem is that I cannot set the map center / extent, because it's calculated as infinity.

Why is the extent method failing?

    proj4.defs('EPSG:23032', '+proj=utm +zone=32 +ellps=intl ' +
      '+towgs84=-87,-98,-121,0,0,0,0 +units=m +no_defs');
    var proj23032 = ol.proj.get('EPSG:23032');
    proj23032.setExtent([-1206118.71, 4021309.92, 1295389.00, 8051813.28]);

    var vectorSource = new ol.source.Vector({
        projection: 'EPSG:23032'
    });

    vectorLayer = new ol.layer.Vector({
        source: vectorSource,
        style: vectorStyleFunction
    });

    map = new ol.Map({
        target: 'map',
        layers: [
            vectorLayer
        ],
        view: new ol.View({
            projection: 'EPSG:23032',
            center: center,
            zoom: 15
        })
    });

    vectorLayer.getSource().addFeature( feature );

    vectorLayer.changed();
    map.updateSize();

    var extent = vectorLayer.getSource().getExtent(); // +- Infinity
    map.getView().fit(extent, map.getSize()); //  Error: https://openlayers.org/en/v4.6.5/doc/errors/#25

Best Answer

Well, this wasn't quite obvious. For anyone having a similar issue, check if you created your feature correctly!

I create the features by parsing data from a FlatBuffers file. Everything was correct, including the geometry data, but I set the geometry outside of the feature constructor. This is what I had (notice that geometry is initialized with null):

    var feature = new ol.Feature({
        id: rawFeature.properties().geoId().toFloat64(),
        layerId: rawFeature.properties().layerId(),
        geometry: null
    });

    feature.geometry = createGeometry(rawFeature);

And this is what works now (notice the geometry is created before, and passed as argument to the constructor:

    var featureGeometry = createGeometry(rawFeature);

    var feature = new ol.Feature({
        id: rawFeature.properties().geoId().toFloat64(),
        layerId: rawFeature.properties().layerId(),
        geometry: featureGeometry
    });

I only came to this solution after feature.getGeometry() was undefined, even though there is a geometry property and it's valid. I'm still puzzled and think this should be considered as a bug.