Wednesday, May 17, 2017

Code snippet: Identify to which polygon a point belong to?

Be The First To Comment
Code sample to find point inside a polygon in shape file using GDAL/OGR 2.x and C#.


using OSGeo.OGR;
using OSGeo.OSR;
using OSGeo.GDAL;
1:  public void FindPolygonBelongsToPoint()   
2:      {  
3:        try   
4:        {  
5:          var shapePath = @"C:\Locations_WGS84.shp";  
6:          Ogr.RegisterAll();  
7:          OSGeo.OGR.Driver shapeDriver = Ogr.GetDriverByName("ESRI Shapefile");  
8:          DataSource shape = shapeDriver.Open(shapePath, 0);  
9:          Layer layer = shape.GetLayerByIndex(0);  
10:    
11:          Feature polygonFeature = layer.GetNextFeature();  
12:    
13:          long featureCountInLayer = layer.GetFeatureCount(1);  
14:          for (int i = 1; i <= featureCountInLayer; i++) {  
15:    
16:            Geometry polygonGeom = polygonFeature.GetGeometryRef();  
17:    
18:            string coordinates = "POINT (-100.726 38.995)";  
19:    
20:            SpatialReference spatialRef = layer.GetSpatialRef();  
21:            Geometry point = Ogr.CreateGeometryFromWkt(ref coordinates, spatialRef);  
22:    
23:            bool isInside = point.Within(polygonGeom);  
24:    
25:            if (isInside)  
26:            {  
27:              var val = polygonFeature.GetFieldAsString(4);  
28:              Console.WriteLine("Found one");  
29:            }  
30:    
31:            polygonFeature = layer.GetNextFeature();            
32:          }         
33:            
34:        }  
35:        catch (Exception ex)   
36:        {  
37:    
38:          Console.WriteLine(ex.Message);  
39:        }          
40:        
41:      }  
 

© 2011 GIS and Remote Sensing Tools, Tips and more .. ToS | Privacy Policy | Sitemap

About Me