OpenLayers 3 - draw polyline vertices only

1.7k Views Asked by At

I'm using OpenLayers 3 and I need to show only the vertices of a polyline. For exemple see this image :

enter image description here

I want to be able to show only the red squares (they can be something else than squares, like circles). Using markers is not an option for performance issue, my lines can be huge (500 000 vertices).

Currently I have a working code :

// Define the style for vertex polyline :
var yellowVertexPolylineStyle = [
    new ol.style.Style({
        image: new ol.style.Circle({
            radius: 1.5,
            fill: new ol.style.Fill({
                color: 'yellow'
            })
        }),
        geometry: function(feature) {
            return new ol.geom.MultiPoint(feature.getGeometry().getCoordinates());
        }
    })
];

// Create the line :
var lineLayer = new ol.layer.Vector({

    zIndex: 1000,
    source: new ol.source.Vector({ features: [new ol.Feature({ geometry: myLine })] }),
    style: yellowVertexPolylineStyle
});

// Add the layer :
map.addLayer(lineLayer);

But this is causing performance issue when the polyline is quite big (> 10 000 points).

Using an ol.geom.MultiPoint geometry is even worse. Does someone knows a better way?

EDIT : I'm trying this now :

// Define the style for vertex polyline :
var yellowVertexPolylineStyle = [
    new ol.style.Style({
        image: new ol.style.Circle({
            radius: 1.5,
            fill: new ol.style.Fill({
                color: 'yellow'
            })
        }),
        geometry: function(feature) {

            var geom = feature.get('stylegeom');
            if (!geom || (geom && geom.getCoordinates().length !== feature.getGeometry().getCoordinates().length) ) {

                geom = new ol.geom.MultiPoint(feature.getGeometry().getCoordinates());
                feature.set('stylegeom', geom);
            }

            return geom;
        }
    })
];

I'll come back here to tell if it works...

1

There are 1 best solutions below

2
ahocevar On

You need to cache your style geometry, otherwise it will be calculated for every rendered frame, e.g.

geometry: function(feature) {
  var geom = feature.get('stylegeom');
  if (!geom) {
    geom = new ol.geom.MultiPoint(feature.getGeometry().getCoordinates());
    feature.set('stylegeom', geom);
  }
  return geom;
}

If your feature geometry changes, you'll need to update the style geometry too:

source.on('changefeature', function(evt) {
  feature.set('stylegeom', undefined);
});