TransWikia.com

OpenLayers Modify interaction on line - use different styles for "Move Vertex" and "Add Vertex"

Geographic Information Systems Asked by seb007 on June 26, 2021

I use OpenLayers 6.5 for my mapping application.

With the Modify Interaction, it is possible to add or move vertices for a line layer. However, the symbol (circle) is the same whether the mouse is over an existing vertex (to be moved) or a non-existing (potential) vertex laying on a line (to be created), see the pictures below.

The is only a single style option for the Modify interaction. Any hint on how to setup a different style for these two types of nodes?

Existing vertex (can be moved)
Existing vertex (can be moved)

Non-existing vertex (can be created)
Non-existing vertex (can be created)

Here is the code for my current Modify interaction, where vectorLayerSource is a LineString vector source:

let modify = new ol.interaction.Modify({
    source: vectorLayerSource,
    deleteCondition: ol.events.condition.shiftKeyOnly,
    insertVertexCondition: ol.events.condition.shiftKeyOnly,
});

One Answer

You can get around the absence of an event by using the features property of the point feature which is passed to a style function by the modify interaction (see the description of style in https://openlayers.org/en/latest/apidoc/module-ol_interaction_Modify-Modify.html) If the coordinates of the point match the coordinates a of vertex on that feature use the style appropriate style for existing node, otherwise use the style for adding a vertex

var modify = new Modify({
  source: source,
  style: function (feature) {
    var point = feature.getGeometry().getCoordinates();
    var geometry = feature.get("features")[0].getGeometry();
    var type = geometry.getType();
    var coordinates =
      type === "Point"
        ? [geometry.getCoordinates()]
        : type === "LineString"
        ? geometry.getCoordinates()
        : type === "Polygon"
        ? geometry.getCoordinates()[0]
        : [];
    var match = false;
    coordinates.forEach(function (coordinate) {
      match =
        match || (coordinate[0] === point[0] && coordinate[1] === point[1]);
    });
    return match ? style1 : style2;
  }
});

https://codesandbox.io/s/draw-and-modify-features-forked-bnmtw

You should avoid having a draw interaction active at the same time as the modify as its style will take precedence.

Correct answer by Mike on June 26, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP