简体   繁体   中英

Openlayers how do you style drawn linestring different than what you are about to draw

I have a openlayers map which has draw interaction. When user starts drawing a linestring on the map, the portion of linestring drawn should look different than what the user would draw next.

In brief when user drops a point on the map, the line till that point should be block, without dash or any other styling options.

To illustrate what I am trying to do here goes the screenshot -

预期产量

We can see user is about to add another point on the line so line till that point should turn block in blue color.

I have maintained the collection of points being added to the map, when user opts to delete the last point, it is being removed from the map but the last segment should also disappear from map. Can't find anything to achieve that.

Also I have added the ol.style.RegularShape() to display a square but it is displaying a circle instead don't know what I am doing wrong.

Here is jsbin link to my code - Draw interaction line style problem

You would need to use a style function for your draw style and divide the geometry into two parts for styling:

var drawStyle = function(feature) {
    var styles = [];
    if (feature.getGeometry().getType() == 'LineString') {
        var coordinates = feature.getGeometry().getCoordinates();
        styles.push(new ol.style.Style({
            geometry: new ol.geom.LineString(coordinates.slice(-2)),
            stroke: new ol.style.Stroke({
                color: '#0000FF',
                lineDash: [1, 20],
                width: 5,
              lineCap:'square',
              lineJoin:'round',
              lineDashOffset:10
            })
        })); 
        styles.push(new ol.style.Style({
            geometry: new ol.geom.MultiPoint(coordinates),
            image: new ol.style.RegularShape({
              points: 4,
              radius: 6,
              angle: Math.PI / 4,
              fill: new ol.style.Fill({
                color: 'blue'
              }),
              stroke: new ol.style.Stroke({
                color: 'blue'
              }),
            })
        })); 
        if (coordinates.length > 2) {
          styles.push(new ol.style.Style({
            geometry: new ol.geom.LineString(coordinates.slice(0,-1)),
            stroke: new ol.style.Stroke({
                color: '#0000FF',
                width: 2,
              lineCap:'square',
              lineJoin:'round'
            })
          }));
        }
    }
    return styles;
}

To remove the last point from the line interaction simply use

line.removeLastPoint();

making sure var line; is declared so it is in the scope of the button click function

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM