0

I'm testing the new OpenLayers v3.15.1 and I've a simple question about styleFunction used to plot GeoJSON. My code contains:

var vectorSource = new ol.source.Vector({
    url: <my geoJson URL>,
    format: new ol.format.GeoJSON({
        defaultDataProjection :'EPSG:4326', 
        projection: 'EPSG:3857'
    })
});

var styleFunction = function(feature) {
    console.log('styleFunction');
    var stroke = new ol.style.Stroke({color: 'black', width: 1});
    var fill = new ol.style.Fill({color: 'red'});
    var geom_name = feature.getGeometry().getType();
    var styles = {
            'Point': new ol.style.Style({
                image: new ol.style.RegularShape({
                    fill: fill,
                    stroke: stroke,
                    points: 3,
                    radius: 7,
                })
            })
        }
    return styles[geom_name];
};

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

My GeoJSON contains more than 500 Point than running the map the first time the styleFunction is executed 500 times; moving the map, it is executed again 500 times and so on.

Looking the JavaScript console, I noticed that every time I move the map or I change the map zoom, the styleFunction is executed. Is this normal? Why the style should be rendered every time I move the map?

  • I've seen examples that modify point radius depending on the resolution dynamicly. So I guess it's normal. – Jose Hermosilla Rodrigo May 22 '16 at 22:06
1

If I am not mistaken...

You are assigning styleFunction(feature) to a vector layer, this as a consequence means that for every feature that is loaded by the vectorSource the styleFunction(feature) is executed.

You are applying the style to the features individually instead of applying a general style to the layer. It's possible to style features individually in OL3, see the documentation on ol.Feature.setStyle and ol.layer.Vector for more info.

So in contrast to what pavlos said, you have to assign a style(without a function) to ol.layer.Vector and not to ol.source.Vector

1

As long as you asign a function to the style this is normal. Function is executed for every single feature. It's time you move the map your features get updated and so function is executed again for every single fetaure.

If you dont want this attitude better asign a proper style instead of a function.

var vectorLayer = new ol.layer.Vector({
    source: vectorSource,
    style: new ol.style.Style({
                stroke: new ol.style.Stroke({
                   color: 'black', 
                   width: 1
                }),
                fill: new ol.style.Fill({
                    color: 'red'
                })
        })
     });

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.