def test_render_from_mapfile(self):
        """ Tmp. quick test, in the future should generate shapefile to use. """
        renderer = MapScriptRenderer()
        mapfile = """
        """

        imgObj = renderer.render_map(
            mapfile="/tmp/mtest/mapfile.map"
        )
        im = Image.open(StringIO(renderer.imgObj_to_bytes(imgObj))).show()
Exemple #2
0
def get_layer_map(project, layer_id, wms_parameters={}, **kwargs):
    """ Get a map image for a given project layer. """

    # @TODO: implicit convention? maybe should centralize layer dir...
    layer_dir = os.path.join(project.static_dir, 'static', 'map_layers', layer_id)

    # Read layer WMS config.
    config_path = os.path.join(layer_dir, 'wms.json')
    with open(config_path, 'rb') as f:
        wms_config = json.load(f)

    # Render w/ GeoTools if using jython.
    if platform.system() == 'Java':
        #@ TODO: implement later...
        pass

    # Otherwise render w/ mapscript.
    else:
        from georefine.util.mapping.ms_renderer import MapScriptRenderer
        renderer = MapScriptRenderer()

        # Rewrite relative paths as needed.
        path_attrs = ['mapfile']
        for path_attr in path_attrs:
            path = wms_config.get(path_attr)
            if path:
                wms_config[path_attr] = os.path.join(layer_dir, path)

        imgObj = renderer.render_map(
            wms_parameters=wms_parameters,
            **wms_config
        )

        img = renderer.imgObj_to_bytes(imgObj)

    return img
Exemple #3
0
def get_data_map(project, query=None, data_entity=None, geom_id_entity=None,
            geom_entity=None, wms_parameters={}, **kwargs):
    """ Get a map image for a given project data map request. """
    dao = manage.get_dao(project)
    wms_parameters['layers'] = 'data'

    if platform.system() == 'Java':
        from georefine.util.mapping.gt_renderer import (
            GeoToolsMapRenderer, mapSqlAlchemyConnectionParameters)
        gt_renderer = GeoToolsMapRenderer()

        sa_connection_parameters = dao.get_connection_parameters()
        gt_connection_parameters = mapSqlAlchemyConnectionParameters(sa_connection_parameters)

        sql = dao.get_sql(query)

        # Render map image.
        img = gt_renderer.renderMap(
            connection_parameters=gt_connection_parameters,
            sql=sql,
            data_entity=data_entity, 
            geom_id_entity=geom_id_entity, 
            geom_entity=geom_entity, 
            map_parameters=wms_parameters,
            **kwargs
        )

    else:
        from georefine.util.mapping.ms_renderer import MapScriptRenderer
        renderer = MapScriptRenderer()


        # Generate data string from parameters.
        # Generate styles from parameters.

        driver = dao.connection.engine.url.drivername
        if 'postgres' in driver:
            connectiontype = 'POSTGIS'

            ms_connection_str = "host=%s password=%s dbname=%s user=%s" % (
                db.engine.url.host, db.engine.url.password, 
                db.engine.url.database, db.engine.url.username)

            sql = dao.get_sql(query)

            ms_data_str = ("geom FROM"
                           " (SELECT ST_SetSRID(subq.%s, 4326) as geom"
                           ", subq.%s as geom_id, *"
                           " FROM (%s) as subq) as wrapped_subq" 
                           " USING UNIQUE geom_id USING srid=4326"
                           % (
                               geom_entity['ID'], 
                               geom_id_entity['ID'],
                               sql
                           )
                          )

        # Spatialite needs some special handling in order to take advantage
        # of spatial indices.
        elif 'sqlite' in driver:
            connectiontype = 'OGR'
            ms_connection_str = dao.connection.engine.url.database

            #frame_entity = {
                #'EXPRESSION': 'func.BuildMbr(%s)' % wms_parameters['BBOX']
            #}
            #query_obj = dao.get_spatialite_spatial_query(
                #query, geom_entity, frame_entity)
            query_obj = dao.get_query(query)
            sql = dao.query_to_raw_sql(query_obj)

            ms_data_str = "SELECT %s AS 'geometry'" % geom_entity['ID']
            if data_entity:
                ms_data_str += ", %s as 'data'" % data_entity['ID']
            ms_data_str += " FROM (%s) AS 'subq'" % sql
            ms_data_str += " WHERE ST_Intersects(geometry, BuildMbr(%s))" % (
                wms_parameters['BBOX'])

        # Create classes for styling if there was a data entity.
        if data_entity:

            # Generate color bins.
            color_bins = cmap.generate_colored_bins(
                schema= 'rgb',
                vmin=data_entity.get('vmin', 0),
                vmax=data_entity.get('vmax', 1),
                num_bins=data_entity.get('num_bins', 20),
                colormap=data_entity.get(
                    'colormap', cmap.generate_hsv_bw_colormap()
                ),
                include_bins=data_entity.get('include_bins', []),
                include_values=data_entity.get('include_values', []),
            )

            # Add bottom/top bins.
            color_bins.insert(0, ((None, color_bins[0][0][0]), color_bins[0][1]))
            color_bins.append(((color_bins[-1][0][1], None), color_bins[-1][1]))

            # Create classes from color bins.
            classes = []
            for color_bin in color_bins:
                bin_ = color_bin[0]
                cmin = bin_[0]
                cmax = bin_[1]
                color = color_bin[1]
                if cmin is not None and cmax is not None:
                    cls = {
                        'expression': "(([data] >= %s) AND ([data] < %s))" % (
                            cmin, cmax),
                        'style': {
                            'color': color
                        }
                    }
                elif cmin is None and cmax is not None:
                    cls = {
                        'expression': "([data] < %s)" % (cmax),
                        'style': {
                            'color': color
                        }
                    }
                elif cmin is not None and cmax is None:
                    cls = {
                        'expression': "([data] >= %s)" % (cmin),
                        'style': {
                            'color': color
                        }
                    }
                classes.append(cls)

        layers = [{
            'name': 'data',
            'connection': ms_connection_str,
            'connectiontype': connectiontype,
            'data': ms_data_str,
            'projection': 'init=epsg:4326',
            'type': 'POLYGON',
            'classes': classes,
        }]

        imgObj = renderer.render_map(
            # use random bg color for transparency
            # Otherwise it defaults to white.
            imagecolor=(253, 27, 92),
            wms_parameters=wms_parameters,
            layers=layers,
        )
        img = renderer.imgObj_to_bytes(imgObj)

    return img