forked from che0/countries
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcountries.py
52 lines (40 loc) · 1.5 KB
/
countries.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from osgeo import ogr
class Point(object):
""" Wrapper for ogr point """
def __init__(self, lat, lng):
""" Coordinates are in degrees """
self.point = ogr.Geometry(ogr.wkbPoint)
self.point.AddPoint(lng, lat)
def getOgr(self):
return self.point
ogr = property(getOgr)
class Country(object):
""" Wrapper for ogr country shape. Not meant to be instantiated directly. """
def __init__(self, shape):
self.shape = shape
def getIso(self):
return self.shape.GetField('ISO2')
iso = property(getIso)
def __str__(self):
return self.shape.GetField('NAME')
def contains(self, point):
return self.shape.geometry().Contains(point.ogr)
class CountryChecker(object):
""" Loads a country shape file, checks coordinates for country location. """
def __init__(self, country_file):
driver = ogr.GetDriverByName('ESRI Shapefile')
self.countryFile = driver.Open(country_file)
self.layer = self.countryFile.GetLayer()
def getCountry(self, point):
"""
Checks given gps-incoming coordinates for country.
Output is either country shape index or None
"""
for i in range(self.layer.GetFeatureCount()):
country = self.layer.GetFeature(i)
if country.geometry().Contains(point.ogr):
return Country(country)
# nothing found
return None