Last active
January 22, 2022 13:10
-
-
Save iamgeoknight/1833d4f933c11207bd48165b26bb9b95 to your computer and use it in GitHub Desktop.
Draw Holes in OpenLayers Polygon
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Create a Draw interaction for LineString and Polygon | |
*/ | |
class Draw { | |
//Constructor accepts geometry type, map object and vector layer | |
constructor(type, map, vector_layer, hole) { | |
this.map = map; | |
this.vector_layer = vector_layer; | |
this.features = []; | |
//Draw feature | |
this.draw = new ol.interaction.Draw({ | |
type: type, | |
stopClick: true, | |
source: vector_layer.getSource() | |
}); | |
if (hole == "hole") { | |
this.draw.on('drawstart', this.onDrawStart); | |
this.draw.on('drawend', this.onDrawEnd); | |
} | |
this.map.addInteraction(this.draw); | |
} | |
/* | |
This function will be called when you start drawing holes | |
*/ | |
onDrawStart = (e) => { | |
//Get Polygon geometry on drawstart that intersects with currently drawing holes. | |
vector_layer.getSource().forEachFeatureIntersectingExtent(e.feature.getGeometry().getExtent(), (f) => { | |
this.intersected = f; | |
}); | |
//Abort Polygon hole drawing when there is no feature underneath it. | |
if (!this.intersected) { | |
alert('No Feature Found to draw holes') | |
e.target.abortDrawing(); | |
return; | |
} | |
this.coords_lenth = this.intersected.getGeometry().getCoordinates().length; | |
//Binding onGeomChange function with drawing feature f. This function will be called only when you are drawing holes over a polygon. | |
e.feature.getGeometry().on('change', this.onGeomChange); | |
} | |
/* | |
This function will be called only when you are drawing holes and it will continously invoked on geometry change. | |
*/ | |
onGeomChange = (e) => { | |
//Get hole coordinates for polygon | |
let linear_ring = new ol.geom.LinearRing(e.target.getCoordinates()[0]); | |
let coordinates = this.intersected.getGeometry().getCoordinates(); | |
let geom = new ol.geom.Polygon(coordinates.slice(0, this.coords_lenth)); | |
//Add hole coordinates to polygon and reset the polygon geometry | |
geom.appendLinearRing(linear_ring); | |
this.intersected.setGeometry(geom); | |
} | |
/* | |
This function will be called when your hole drawing is finished. | |
*/ | |
onDrawEnd =(e) => { | |
setTimeout(() => { | |
vector_layer.getSource().removeFeature(e.feature); | |
}, 5); | |
this.intersected = undefined; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment