Skip to content

Instantly share code, notes, and snippets.

@stevenchanin
Created June 19, 2020 18:28
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stevenchanin/f69b50deea359edd2dc6bc5944950e5a to your computer and use it in GitHub Desktop.
Save stevenchanin/f69b50deea359edd2dc6bc5944950e5a to your computer and use it in GitHub Desktop.
OpenLayers - Find point on polygon near mouse click
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;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment