Ejemplo n.º 1
0
 def __init__(self, proj):
   if isinstance(proj, CRS):
     self._crs = proj
   elif isinstance(proj, Projection):
     self._crs = proj._crs
   elif isinstance(proj, (str,unicode)):
     try:
        self._crs = crs.decode(proj)
     except:
        try:
          self._crs = crs.parseWKT(proj)
        except:
          raise Exception('Unable to determine projection from %s' % proj)
Ejemplo n.º 2
0
 def __init__(self, proj):
     if isinstance(proj, CRS):
         self._crs = proj
     elif isinstance(proj, Projection):
         self._crs = proj._crs
     elif isinstance(proj, (str, unicode)):
         try:
             self._crs = crs.decode(proj)
         except:
             try:
                 self._crs = crs.parseWKT(proj)
             except:
                 raise Exception('Unable to determine projection from %s' %
                                 proj)
Ejemplo n.º 3
0
    def get_crs(clz, crs):
        """ Converts crs definition to GeoTools CRS obj. """
        if isinstance(crs, CoordinateReferenceSystem):
            return crs

        # @TODO
        # Eventually should add handling for
        # proj4 strings, dicts.

        if isinstance(crs, str) or isinstance(crs, unicode):
            if crs.startswith('EPSG:'):
                return CRS.decode(crs)
            # Otherwise assume WKT.
            else:
                return CRS.parseWKT(crs)
Ejemplo n.º 4
0
 def getbounds(self):
     from geoscript.geom.bounds import Bounds
     #extent = crs.getGeographicBoundingBox(self._crs)
     env = crs.getEnvelope(self._crs)
     if env:
         return Bounds(env.getMinimum(0), env.getMinimum(1),
                       env.getMaximum(0), env.getMaximum(1), self)
Ejemplo n.º 5
0
 def getbounds(self):
   from geoscript.geom.bounds import Bounds
   #extent = crs.getGeographicBoundingBox(self._crs)  
   env = crs.getEnvelope(self._crs)
   if env:
     return Bounds(env.getMinimum(0), env.getMinimum(1), 
       env.getMaximum(0), env.getMaximum(1), self)
Ejemplo n.º 6
0
 def getgeobounds(self):
     from geoscript.geom.bounds import Bounds
     box = crs.getGeographicBoundingBox(self._crs)
     if box:
         return Bounds(box.westBoundLongitude, box.southBoundLatitude,
                       box.eastBoundLongitude, box.northBoundLatitude,
                       'epsg:4326')
Ejemplo n.º 7
0
def projections():
    """
  Iterator over all defined projections::

    for p in proj.projections():
       ..

  This function returns :class:`Projection` objects.

  """
    for code in crs.getSupportedCodes('epsg'):
        try:
            yield Projection('epsg:%s' % code)
        except:
            # todo: log this
            pass
Ejemplo n.º 8
0
def projections():
  """
  Iterator over all defined projections::

    for p in proj.projections():
       ..

  This function returns :class:`Projection` objects.

  """
  for code in crs.getSupportedCodes('epsg'):
     try:
       yield Projection('epsg:%s' % code)
     except:
       # todo: log this
       pass
Ejemplo n.º 9
0
    def transform(self, obj, dest):
        """
    Transforms an object from this projection to a specified destination projection.

    *obj* is a :class:`Geometry <geoscript.geom.Geometry>` object to transform.

    *dest* is the destination :class:`Projection` to transform to.

     >>> proj = Projection('epsg:4326')
     >>> dest = Projection('epsg:3005')
     >>> import geom
     >>> p1 = geom.Point(-125, 50)
     >>> p2 = proj.transform(p1, dest)
     >>> p2.round()
     POINT (1071693 554290)


    *obj* may also be specified as a single coordinate ``list`` or ``tuple``. *dest* may also be specified as a string identifying the destination projection.

    >>> proj = Projection('epsg:4326')
    >>> p1 = (-125, 50)
    >>> p2 = proj.transform(p1, 'epsg:3005')
    >>> [round(x) for x in p2]
    [1071693.0, 554290.0]
    """
        fromcrs = self._crs
        tocrs = Projection(dest)._crs
        tx = crs.findMathTransform(fromcrs, tocrs)

        if isinstance(obj, (list, tuple)):
            # tuple or list
            import jarray
            transformed = jarray.zeros(len(obj), 'd')
            tx.transform(obj, 0, transformed, 0, 1)
            l = [transformed[x] for x in range(len(obj))]
            return l if isinstance(obj, list) else tuple(l)
        else:
            # geometry
            gt = GeometryTX()
            gt.mathTransform = tx

            return core.map(gt.transform(obj))
Ejemplo n.º 10
0
  def transform(self, obj, dest):
    """
    Transforms an object from this projection to a specified destination projection.

    *obj* is a :class:`Geometry <geoscript.geom.Geometry>` object to transform.

    *dest* is the destination :class:`Projection` to transform to.

     >>> proj = Projection('epsg:4326')
     >>> dest = Projection('epsg:3005')
     >>> import geom
     >>> p1 = geom.Point(-125, 50)
     >>> p2 = proj.transform(p1, dest)
     >>> p2.round()
     POINT (1071693 554290)


    *obj* may also be specified as a single coordinate ``list`` or ``tuple``. *dest* may also be specified as a string identifying the destination projection.

    >>> proj = Projection('epsg:4326')
    >>> p1 = (-125, 50)
    >>> p2 = proj.transform(p1, 'epsg:3005')
    >>> [round(x) for x in p2]
    [1071693.0, 554290.0]
    """
    fromcrs = self._crs
    tocrs = Projection(dest)._crs
    tx = crs.findMathTransform(fromcrs,tocrs)

    if isinstance(obj, (list,tuple)):
      # tuple or list
      import jarray
      transformed = jarray.zeros(len(obj), 'd')
      tx.transform(obj, 0, transformed, 0, 1)
      l = [transformed[x] for x in range(len(obj))]
      return l if isinstance(obj, list) else tuple(l)
    else:
      # geometry
      gt = GeometryTX()
      gt.mathTransform = tx

      return core.map(gt.transform(obj))
Ejemplo n.º 11
0
 def getid(self):
     return str(crs.lookupIdentifier(self._crs, True))
Ejemplo n.º 12
0
 def __eq__(self, other):
     return crs.equalsIgnoreMetadata(self._crs, other._crs)
Ejemplo n.º 13
0
 def getgeobounds(self):
   from geoscript.geom.bounds import Bounds
   box = crs.getGeographicBoundingBox(self._crs)  
   if box:
     return Bounds(box.westBoundLongitude, box.southBoundLatitude, 
       box.eastBoundLongitude, box.northBoundLatitude, 'epsg:4326')
Ejemplo n.º 14
0
 def getid(self):
   return str(crs.lookupIdentifier(self._crs, True))
Ejemplo n.º 15
0
 def __eq__(self, other):
   return crs.equalsIgnoreMetadata(self._crs, other._crs)
Ejemplo n.º 16
0
    def renderMap(self, connection_parameters=None, sql=None, geom_id_entity=None, geom_entity=None, data_entity=None, map_parameters={}):

        # Put connection parameters into a java HashMap.
        params_hashmap = HashMap()
        for param, value in connection_parameters.items():
            if value:
                params_hashmap.put(param, value)

        # Get data store.
        data_store = DataStoreFinder.getDataStore(params_hashmap)

        # Create VirtualTable from sql.
        vtable = VirtualTable("vtable", sql)

        # Set primary key.
        vtable.setPrimaryKeyColumns([geom_id_entity['ID']])

        # metadatata = intententional typo. GT needs to fix the name.
        vtable.addGeometryMetadatata(geom_entity['ID'], JPolygon, 4326)

        # Create feature source from virtual table.
        data_store.addVirtualTable(vtable)
        feature_source = data_store.getFeatureSource("vtable")

        # Add styling classes if there was a value entity.
        if data_entity:
            # Generate class bounds.
            num_classes = data_entity.get('num_classes', 25)
            vmin = float(data_entity.get('min', 0))
            vmax = float(data_entity.get('max', 1))
            vrange = vmax - vmin
            class_width = vrange/num_classes
            classes = [(None, vmin)]
            for i in range(num_classes):
                classes.append((vmin + i * class_width, vmin + (i + 1) * class_width))
            classes.append((vmax, None))

            # Generate style rules for classes.
            rules = []
            for c in classes:
                rule = self.create_rule(c[0], c[1], vmin, vrange, attr=data_entity['ID'])
                rules.append(rule)
            feature_type_style = self.style_factory.createFeatureTypeStyle(rules)
            style = self.style_factory.createStyle()
            style.featureTypeStyles().add(feature_type_style)
        else:
            style = None

        # Setup map.
        gt_map = DefaultMapContext()
        gt_map.addLayer(feature_source, style)
        gt_renderer = StreamingRenderer()
        gt_renderer.setMapContent(gt_map)
        image_bounds = Rectangle(0, 0, map_parameters.get('WIDTH', 100), map_parameters.get('HEIGHT', 100))

        # Set image type based on format.
        image_format = map_parameters.get('FORMAT', 'image/png')
        if image_format == 'image/jpeg':
            image_type = BufferedImage.TYPE_INT_RGB
        else:
            image_type = BufferedImage.TYPE_INT_ARGB

        buffered_image = BufferedImage(image_bounds.width, image_bounds.height, image_type)
        graphics = buffered_image.createGraphics()

        # Set background color if not transparent.
        if not map_parameters.get('TRANSPARENT'):
            graphics.setPaint(Color.WHITE)
            graphics.fill(image_bounds)

        crs = CRS.decode(map_parameters.get('SRS', "EPSG:4326"))
        bbox = map_parameters.get('BBOX', '-180,-90,180,90')
        coords = [float(coord) for coord in bbox.split(",")]
        map_bounds = ReferencedEnvelope(coords[0], coords[2], coords[1], coords[3], crs)

        gt_renderer.paint(graphics, image_bounds, map_bounds)

        # Release the JDBC connection and map content.
        data_store.dispose()
        gt_renderer.getMapContent().dispose()

        # Return raw image.
        byte_array_output_stream = ByteArrayOutputStream()
        informal_format = re.match('image/(.*)', image_format).group(1)
        ImageIO.write(buffered_image, informal_format, byte_array_output_stream)
        byte_array = byte_array_output_stream.toByteArray()
        raw_image = Py.newString(StringUtil.fromBytes(byte_array))
        return raw_image
Ejemplo n.º 17
0
 def getbounds(self):
   from geoscript.geom.bounds import Bounds
   extent = crs.getGeographicBoundingBox(self._crs)  
   if extent:
     return Bounds(extent.westBoundLongitude, extent.southBoundLatitude, 
       extent.eastBoundLongitude, extent.northBoundLatitude, 'epsg:4326')
Ejemplo n.º 18
0
 def get_transform(clz, crs1, crs2):
     crs1 = clz.get_crs(crs1)
     crs2 = clz.get_crs(crs2)
     return CRS.findMathTransform(crs1, crs2, True)