TransWikia.com

Modify circle but don't allow to change center in OpenLayers

Geographic Information Systems Asked by quikina on February 22, 2021

I have a Circle on my map with the following modify code:

var modify = new Modify({
            source: this.getRadiusLayer().getSource(),
            wrapX: true,
            style: new Style({
                stroke: new Stroke({color:'#AA0000', width:2}),
                fill: new Fill({color: '#AA000059'}),
                image: new CircleStyle({radius:5, fill: new Fill({color: '#AA0000'})})
            }),
        })

I want my users to be able to change the radius of the circle, but I don’t want them to be able to change the center point of the circle. Is there any way I can disable moving the circle to another center point in version 6.4.3?

One Answer

I found a rather primitive way of achieving this by using condition option of modify interaction as a filter that prevents modify action if clicked position is too close to existing circle center. Too close here means nearer that snap distance, which has default value of 10 pixels.

Code can then look something like this (ES5):

var source = this.getRadiusLayer().getSource();

var pixel;
function modifyCondition(evt) {
  var retVal = ol.events.condition.primaryAction;
  pixel = evt.pixel_;
  source.forEachFeature(function(feature) {
    if (feature.getGeometry().getType() == 'Circle') {
      var center = feature.getGeometry().getCenter();
      var centerPixel = map.getPixelFromCoordinate(center);
      if ((Math.abs(pixel[0] - centerPixel[0]) < 10) && (Math.abs(pixel[1] - centerPixel[1]) < 10)) {
        retVal = false;
        return(true);
      }
    }
  });
  return(retVal);
}

var modify = new ol.interaction.Modify({
  source: source,
  condition: modifyCondition
});

Correct answer by TomazicM on February 22, 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