src/pyams_gis/area.py
changeset 0 c73bb834ccbe
child 71 8a73283378e1
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/pyams_gis/area.py	Thu May 18 17:23:48 2017 +0200
@@ -0,0 +1,60 @@
+#
+# Copyright (c) 2008-2017 Thierry Florac <tflorac AT ulthar.net>
+# All Rights Reserved.
+#
+# This software is subject to the provisions of the Zope Public License,
+# Version 2.1 (ZPL).  A copy of the ZPL should accompany this distribution.
+# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
+# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
+# FOR A PARTICULAR PURPOSE.
+#
+
+__docformat__ = 'restructuredtext'
+
+
+# import standard library
+try:
+    from osgeo.osr import SpatialReference, CoordinateTransformation
+    have_gdal = True
+except ImportError:
+    have_gdal = False
+from persistent import Persistent
+
+# import interfaces
+from pyams_gis.interfaces import WGS84, IGeoArea
+
+# import packages
+from zope.interface import implementer
+from zope.schema.fieldproperty import FieldProperty
+
+
+@implementer(IGeoArea)
+class GeoArea(Persistent):
+    """GeoArea attribute object"""
+
+    x1 = FieldProperty(IGeoArea['x1'])
+    y1 = FieldProperty(IGeoArea['y1'])
+    x2 = FieldProperty(IGeoArea['x2'])
+    y2 = FieldProperty(IGeoArea['y2'])
+    projection = FieldProperty(IGeoArea['projection'])
+
+    def __bool__(self):
+        return bool(self.x1 and self.y1 and self.x2 and self.y2)
+
+    def get_coordinates(self, projection=WGS84):
+        if projection == self.projection:
+            return (self.x1, self.y1), (self.x2, self.y2)
+        if (not have_gdal) or not self:
+            return None, None
+        source = SpatialReference()
+        source.ImportFromEPSG(self.projection)
+        destination = SpatialReference()
+        destination.ImportFromEPSG(projection)
+        transformation = CoordinateTransformation(source, destination)
+        return transformation.TransformPoint(float(self.x1), float(self.y1))[0:2], \
+               transformation.TransformPoint(float(self.x2), float(self.y2))[0:2]
+
+    @property
+    def wgs_coordinates(self):
+        return self.get_coordinates(WGS84)