JavaScript

Why OpenLayers3 does not render my GeoJSON?

OpenLayers3 offers the ol.source.GeoJSON class that allows to read data from a GeoJSON source (an URL, a JavaScript object or a text string).

Maybe you, like me, has spent some time trying to understand why your GeoJSON data is not rendering properly: projection is fine, your GeoJSON is well formed and validated but OpenLayers3 doesn’t return any features and so nothing is rendered in the map.
 
 
 
 

What is the problem?

0d1aff07

The ol.source.GeoJSON class is a subclass of ol.source.StaticVector that uses an ol.format.GeoJSON instance to read content:

A source class, by definition, acts as a source of features for a vector layers, that is, it is like a container of features. Because of this, the ol.source.GeoJSON source is limited to read GeoJSON features and not geometries. So next GeoJSON will be ignored by OpenLayers3 (really if you use de debug version you will see an assertion message):

{
    "type": "Point",
    "coordinates": [
        -105.01621,
        39.57422
    ]
} 

While the next is a valid GeoJSON suitable to be read by the source:

{
    "type": "Feature",
    "geometry": {        
        "type": "Point",
        "coordinates": [
            -105.01621,
            39.57422
        ]
    },
    "properties": {
        "name": "Some feature property"
    }
} 

 That means we can’t read GeoJSON geometries?

Absolutely no, simply means source classes follows the source concept, and that means, work with features.

The ol.format.GeoJSON format class allows to read and write features and geometries. To read a GeoJSON file composed of geometries we need to read the geometries and, manually, create a feature for each one. For example:

var point = {
    "type": "Point",
    "coordinates": [
        -105.01621,
        39.57422
    ]
};
 
// Read the GeoJSON geometries using the format class
var format = new ol.format.GeoJSON();
var geometry = format.readGeometry(point);
 
// Create a feature using the geometry
var feature = new ol.Feature({
  geometry: geometry,
  propA: 'Some feature property'
});
 
// Add feature to the source of some vector layer
vectorLayer.getSource().addFeature(feature); 
Reference: Why OpenLayers3 does not render my GeoJSON? from our WCG partner Antonio Santiago at the A Curious Animal blog.

Antonio Santiago

A Computer Science as profession and hobby. Firm believer of Software Engineering and a lover of Agile methodologies. There is no ring to rule them all, every place needs to forge its own master ring. His main field of experience is the Java ecosystem, and he has also worked actively with many related web technologies while looking to improve the client side of web applications.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button