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 | |
| */ | |
| onDrawStart = (e) => { | |
| vector_layer.getSource().forEachFeatureIntersectingExtent(e.feature.getGeometry().getExtent(), (f) => { | |
| this.intersected = f; | |
| }); | |
| 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 | |
| e.feature.getGeometry().on('change', this.onGeomChange); | |
| } | |
| /* | |
| This function will called when ever there will be a change in geometry like increase in length, area, position, | |
| */ | |
| 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 you start drawing | |
| */ | |
| 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