Skip to content

Instantly share code, notes, and snippets.

@stevenchanin
Created June 19, 2020 18:28
Show Gist options
  • Select an option

  • Save stevenchanin/f69b50deea359edd2dc6bc5944950e5a to your computer and use it in GitHub Desktop.

Select an option

Save stevenchanin/f69b50deea359edd2dc6bc5944950e5a to your computer and use it in GitHub Desktop.

Revisions

  1. stevenchanin created this gist Jun 19, 2020.
    58 changes: 58 additions & 0 deletions Modify Event
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,58 @@
    this.modifyInteraction = new Modify({
    // source: this.vectorSource, // all features in vector source
    features: this.selectInteraction.getFeatures(), // only selected features

    condition: (event) => {
    // clear out all selectedVertex properties on all features
    this.vectorLayer.getSource().forEachFeature((feature) => {
    feature.set("selectedVertex", undefined);
    });

    console.log("Modify Condition Fired:", event);
    const nearbyFeatures = this.map.getFeaturesAtPixel(event.pixel, { hitTolerance: 10 });
    console.log("Nearby features", nearbyFeatures);

    if (nearbyFeatures.length) {
    const eventPixel = event.pixel;
    const closestFeature = nearbyFeatures[0];
    const closestFeatureGeometry = closestFeature.getGeometry();
    const geometryType = closestFeatureGeometry.constructor.name;
    if (geometryType !== "Polygon") return true;

    const coordinatesOnClosestFeature = closestFeatureGeometry.getCoordinates()[0];
    const nearbyVertex = this.findVertexCloseEnoughToEvent(eventPixel, coordinatesOnClosestFeature);
    if (nearbyVertex) {
    console.log("Closest Feature:", closestFeature, "Closest vertex coordinates:", nearbyVertex);
    closestFeature.set("selectedVertex", nearbyVertex);
    } else {
    console.log("Closest Feature:", closestFeature, "Closest vertex coordinates:", "All are far away");
    }
    } else {
    console.log("all features are far away");
    }
    return true;
    },
    });

    findVertexCloseEnoughToEvent(eventPixel, coordinatesOnClosestFeature) {
    let minDistance;
    let closestCoordinate;

    coordinatesOnClosestFeature.forEach((coordinate) => {
    const coordinatePixels = this.map.getPixelFromCoordinate(coordinate);
    const dx = eventPixel[0] - coordinatePixels[0];
    const dy = eventPixel[1] - coordinatePixels[1];
    const distance = Math.sqrt(dx * dx + dy * dy);

    if (minDistance === undefined || distance < minDistance) {
    minDistance = distance;
    closestCoordinate = coordinate;
    }
    });

    if (minDistance < 20) {
    return closestCoordinate;
    } else {
    return undefined;
    }
    }