Last active
August 29, 2015 14:24
-
-
Save alexrutherford/988a53e918040c379746 to your computer and use it in GitHub Desktop.
Gist for polygon hit detection in shapefiles
This file contains 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
import glob | |
import shapefile | |
from matplotlib.path import Path | |
class HitDetector(): | |
''' | |
Class to test if an arbitrary (lat,long) point | |
is within the boundary of a country outline | |
and which region it belongs in. Uses shapefiles | |
from gadm.org | |
''' | |
def init(self,path='.'): | |
print 'Initialising' | |
self.regionFile=path+'/NPL_adm1' | |
self.countryFile=path+'/NPL_adm0' | |
# File names hardcoded | |
print self.regionFile,self.countryFile | |
self.regionShapes=shapefile.Reader(self.regionFile) | |
self.countryShape=shapefile.Reader(self.countryFile) | |
self.countryPath=Path(self.countryShape.shape().points) | |
def isInCountry(self,point): | |
return self.countryPath.contains_point(point) | |
def getRegion(self,point,v=True): | |
for shape,record in zip(self.regionShapes.shapes(),self.regionShapes.records()): | |
print record[3],record[4] | |
# 3 is region index and 4 is name | |
if Path(shape.points).contains_point(point): | |
if v:print 'Hit detected' | |
return record[3],record[4] | |
if self.isInCountry(point): | |
if v:print 'Point is in gap' | |
return 5,'West' | |
# Strangely, there is a gap between the regions' shapes (Nepal only) | |
# If it falls in the gap, should belong to Western | |
return None,None |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment