Ejemplo n.º 1
0
    def test_subquery():
        ds = mapnik.PostGIS(dbname=MAPNIK_TEST_DBNAME,
                            table='(select * from world_merc) as w')
        fs = ds.featureset()
        feature = fs.next()
        eq_(feature['gid'], 1)
        eq_(feature['fips'], u'AC')
        eq_(feature['iso2'], u'AG')
        eq_(feature['iso3'], u'ATG')
        eq_(feature['un'], 28)
        eq_(feature['name'], u'Antigua and Barbuda')
        eq_(feature['area'], 44)
        eq_(feature['pop2005'], 83039)
        eq_(feature['region'], 19)
        eq_(feature['subregion'], 29)
        eq_(feature['lon'], -61.783)
        eq_(feature['lat'], 17.078)
        eq_(ds.describe()['geometry_type'], mapnik.DataGeometryType.Polygon)

        ds = mapnik.PostGIS(
            dbname=MAPNIK_TEST_DBNAME,
            table='(select gid,geom,fips as _fips from world_merc) as w')
        fs = ds.featureset()
        feature = fs.next()
        eq_(feature['gid'], 1)
        eq_(feature['_fips'], u'AC')
        eq_(len(feature), 2)
        eq_(ds.describe()['geometry_type'], mapnik.DataGeometryType.Polygon)
Ejemplo n.º 2
0
    def test_psql_error_should_not_break_connection_pool():
        # Bad request, will trigger an error when returning result
        ds_bad = mapnik.PostGIS(
            dbname=MAPNIK_TEST_DBNAME,
            table=
            """(SELECT geom as geom,label::int from test11) as failure_table""",
            max_async_connection=5,
            geometry_field='geom',
            srid=4326)

        # Good request
        ds_good = mapnik.PostGIS(dbname=MAPNIK_TEST_DBNAME,
                                 table="test",
                                 max_async_connection=5,
                                 geometry_field='geom',
                                 srid=4326)

        # This will/should trigger a PSQL error
        failed = False
        try:
            fs = ds_bad.featureset()
            for feature in fs:
                pass
        except RuntimeError:
            failed = True

        eq_(failed, True)

        # Should be ok
        fs = ds_good.featureset()
        count = 0
        for feature in fs:
            count += 1
        eq_(count, 8)
Ejemplo n.º 3
0
    def test_psql_error_should_give_back_connections_opened_for_lower_layers_to_the_pool():
        map1 = mapnik.Map(600,300)
        s = mapnik.Style()
        r = mapnik.Rule()
        r.symbols.append(mapnik.PolygonSymbolizer())
        s.rules.append(r)
        map1.append_style('style',s)

        # This layer will fail after a while
        buggy_s = mapnik.Style()
        buggy_r = mapnik.Rule()
        buggy_r.symbols.append(mapnik.PolygonSymbolizer())
        buggy_r.filter = mapnik.Filter("[fips] = 'FR'")
        buggy_s.rules.append(buggy_r)
        map1.append_style('style for buggy layer',buggy_s)
        buggy_layer = mapnik.Layer('this layer is buggy at runtime')
        # We ensure the query wille be long enough
        buggy_layer.datasource = mapnik.PostGIS(dbname=MAPNIK_TEST_DBNAME,table='(SELECT geom as geom, pg_sleep(0.1), fips::int from world_merc) as failure_tabl',
            max_async_connection=2, max_size=2,asynchronous_request = True, geometry_field='geom')
        buggy_layer.styles.append('style for buggy layer')

        # The query for this layer will be sent, then the previous layer will raise an exception before results are read
        forced_canceled_layer = mapnik.Layer('this layer will be canceled when an exception stops map rendering')
        forced_canceled_layer.datasource = mapnik.PostGIS(dbname=MAPNIK_TEST_DBNAME,table='world_merc',
            max_async_connection=2, max_size=2, asynchronous_request = True, geometry_field='geom')
        forced_canceled_layer.styles.append('style')

        map1.layers.append(buggy_layer)
        map1.layers.append(forced_canceled_layer)
        map1.zoom_all()
        map2 = mapnik.Map(600,300)
        map2.background = mapnik.Color('steelblue')
        s = mapnik.Style()
        r = mapnik.Rule()
        r.symbols.append(mapnik.LineSymbolizer())
        r.symbols.append(mapnik.LineSymbolizer())
        s.rules.append(r)
        map2.append_style('style',s)
        layer1 = mapnik.Layer('layer1')
        layer1.datasource = mapnik.PostGIS(dbname=MAPNIK_TEST_DBNAME,table='world_merc',
            max_async_connection=2, max_size=2, asynchronous_request = True, geometry_field='geom')
        layer1.styles.append('style')
        map2.layers.append(layer1)
        map2.zoom_all()

        # We expect this to trigger a PSQL error
        try:
            mapnik.render_to_file(map1,'/tmp/mapnik-postgis-test-map1.png', 'png')
            # Test must fail if error was not raised just above
            eq_(False,True)
        except RuntimeError:
            pass
        # This used to raise an exception before correction of issue 2042
        mapnik.render_to_file(map2,'/tmp/mapnik-postgis-test-map2.png', 'png')
Ejemplo n.º 4
0
    def test_auto_detection_will_fail_since_no_primary_key():
        ds = mapnik.PostGIS(dbname=MAPNIK_TEST_DBNAME,
                            table='test3',
                            geometry_field='geom',
                            autodetect_key_field=False)
        fs = ds.featureset()
        feat = fs.next()
        eq_(feat['manual_id'], 0)
        # will fail: https://github.com/mapnik/mapnik/issues/895
        #eq_(feat['non_id'],9223372036854775807)
        eq_(fs.next()['manual_id'], 1)
        eq_(fs.next()['manual_id'], 1000)
        eq_(fs.next()['manual_id'], -1000)
        eq_(fs.next()['manual_id'], 2147483647)
        eq_(fs.next()['manual_id'], -2147483648)

        # since no valid primary key will be detected the fallback
        # is auto-incrementing counter
        fs = ds.featureset()
        eq_(fs.next().id(), 1)
        eq_(fs.next().id(), 2)
        eq_(fs.next().id(), 3)
        eq_(fs.next().id(), 4)
        eq_(fs.next().id(), 5)
        eq_(fs.next().id(), 6)
Ejemplo n.º 5
0
 def test_querying_subquery_with_mixed_case():
     ds = mapnik.PostGIS(dbname=MAPNIK_TEST_DBNAME,table='(SeLeCt * FrOm "tableWithMixedCase") as MixedCaseQuery',
                         geometry_field='geom',
                         autodetect_key_field=True)
     fs = ds.featureset()
     for id in range(1,5):
         eq_(fs.next().id(),id)
Ejemplo n.º 6
0
 def test_disabled_auto_detection_and_subquery():
     ds = mapnik.PostGIS(
         dbname=MAPNIK_TEST_DBNAME,
         table='''(select geom, 'a'::varchar as name from test2) as t''',
         geometry_field='geom',
         autodetect_key_field=False)
     fs = ds.featureset()
     feat = fs.next()
     eq_(feat.id(), 1)
     eq_(feat['name'], 'a')
     feat = fs.next()
     eq_(feat.id(), 2)
     eq_(feat['name'], 'a')
     feat = fs.next()
     eq_(feat.id(), 3)
     eq_(feat['name'], 'a')
     feat = fs.next()
     eq_(feat.id(), 4)
     eq_(feat['name'], 'a')
     feat = fs.next()
     eq_(feat.id(), 5)
     eq_(feat['name'], 'a')
     feat = fs.next()
     eq_(feat.id(), 6)
     eq_(feat['name'], 'a')
Ejemplo n.º 7
0
def create_map():
    map = mapnik.Map(800, 600)

    map.background = mapnik.Color('rgb(0,0,0,0)')

    style = mapnik.Style()
    rule_orange = create_rule('([productivi] > 30) and ([productivi] < 70)',
                              (250, 100, 0))
    rule_green = create_rule('[productivi] >= 70', (0, 250, 0))
    rule_red = create_rule('[productivi] <= 30', (250, 0, 0))

    style.rules.extend([rule_green, rule_red, rule_orange])
    map.append_style('tracking_points', style)

    layer = mapnik.Layer('tracking_points')
    db_settings = DATABASES['default']
    layer.datasource = mapnik.PostGIS(host=db_settings['HOST'],
                                      port=db_settings['PORT'],
                                      user=db_settings['USER'],
                                      password=db_settings['PASSWORD'],
                                      dbname=db_settings['NAME'],
                                      table='paints')
    layer.styles.append('tracking_points')
    map.layers.append(layer)
    map.zoom_all()
    return map
Ejemplo n.º 8
0
 def create_ds():
     ds = mapnik.PostGIS(dbname=MAPNIK_TEST_DBNAME,
                         table='test',
                         max_size=20,
                         geometry_field='geom')
     fs = ds.all_features()
     eq_(len(fs), 8)
Ejemplo n.º 9
0
    def addPreviewOfGeneralizedGeometriesToMap(self, table_name, symbol_type,
                                               layerSRS, name):
        genColor = 'rgb(0%,0%,100%)'
        s = mapnik.Style()
        r = mapnik.Rule()
        if symbol_type == 'polygon':
            polygon_symbolizer = mapnik.PolygonSymbolizer(
                mapnik.Color(genColor))
            r.symbols.append(polygon_symbolizer)
        elif symbol_type == 'line':
            line_symbolizer = mapnik.LineSymbolizer(mapnik.Color(genColor), 2)
            r.symbols.append(line_symbolizer)
        else:
            print symbol_type, 'has to be implemented to preview!!!'
        s.rules.append(r)
        self.tileParams.getMapnikMap().append_style(name, s)

        lyr = mapnik.Layer('Generalized geometry from PostGIS')
        lyr.datasource = mapnik.PostGIS(host='localhost',
                                        user='******',
                                        password='******',
                                        dbname='meingis',
                                        table='(select geom from ' +
                                        table_name + ' ) as geometries')
        lyr.srs = layerSRS
        lyr.styles.append(name)
        self.tileParams.getMapnikMap().layers.append(lyr)
Ejemplo n.º 10
0
 def get_mapnik_ds(self, **kwargs):
     if not self.geometry_field:
         raise ValueError('Geometry field not found')
     if kwargs.get('settings'):
         params_ = kwargs.get('settings').copy()
     else:
         if hasattr(self.qs, '_db'):
             # we use qs._db here instead of qs.db because it
             # evaluates to None if using default db
             params_ = get_base_params(using=self.qs._db)
         else:
             params_ = get_base_params()
     subquery = self._as_mapnik_sql(**kwargs)
     sub_low = subquery.lower()
     # requires >= Mapnik 0.7.0
     if 'where' in sub_low or sub_low.count('from') > 1:
         params_['extent_from_subquery'] = True
     else:
         params_['extent_from_subquery'] = False
     params_['table'] = str(subquery)
     params_['geometry_field'] = str(self.geometry_field.name)
     params_['srid'] = int(self.geometry_field.srid)
     params_['persist_connection'] = self.persist_connection
     ds = mapnik.PostGIS(**params_)
     ds.subquery = subquery
     return ds
Ejemplo n.º 11
0
 def create_ds_and_error():
     try:
         ds = mapnik.PostGIS(dbname=MAPNIK_TEST_DBNAME,
                             table='asdfasdfasdfasdfasdf',
                             max_size=20)
         fs = ds.all_features()
     except: pass
Ejemplo n.º 12
0
    def layer(self, layer_ids=None, request=None):
        """Return mapnik layers and styles."""
        layers = []
        styles = {}

        style = mapnik.Style()
        styles["segmentadapterstyle"] = style

        rule = mapnik.Rule()
        symbol = mapnik.LineSymbolizer(mapnik.Color(255, 100, 100), 4)
        rule.symbols.append(symbol)
        style.rules.append(rule)

        query = """(
            select segment.the_geom
            from lizard_rijnmond_segment segment
        ) as data"""
        default_database = settings.DATABASES['default']
        datasource = mapnik.PostGIS(
            host=default_database['HOST'],
            user=default_database['USER'],
            password=default_database['PASSWORD'],
            dbname=default_database['NAME'],
            table=query,
        )

        layer = mapnik.Layer("Segments", coordinates.RD)
        layer.datasource = datasource
        layer.styles.append("segmentadapterstyle")
        layers.append(layer)

        return layers, styles
Ejemplo n.º 13
0
    def __add_manholes(self, layers, styles):
        "Add manhole layer and styles."

        # Select the manholes that are part of this sewerage.

        manholes = Manhole.objects.filter(sewerage__pk=self.id)

        # Define a style.

        style = mapnik.Style()

        # Style the `normal` manholes.

        rule = mapnik.Rule()
        rule.filter = mapnik.Filter("[sink] != 1")
        symbol = mapnik.PointSymbolizer()
        symbol.allow_overlap = True
        rule.symbols.append(symbol)
        style.rules.append(rule)

        # Style the sink.

        rule = mapnik.Rule()
        rule.filter = mapnik.Filter("[sink] = 1")
        symbol = mapnik.PointSymbolizer(
            str(finders.find("lizard_riool/sink.png")), "png", 8, 8
        )
        symbol.allow_overlap = True
        rule.symbols.append(symbol)
        style.rules.append(rule)

        # Add labels.

        rule = mapnik.Rule()
        rule.max_scale = 1700
        symbol = mapnik.TextSymbolizer(
            'code', 'DejaVu Sans Book', 10, mapnik.Color('black')
        )
        symbol.allow_overlap = True
        symbol.label_placement = mapnik.label_placement.POINT_PLACEMENT
        symbol.vertical_alignment = mapnik.vertical_alignment.TOP
        symbol.displacement(0, -5)  # slightly above
        rule.symbols.append(symbol)
        style.rules.append(rule)

        # Setup datasource.

        params = default_database_params()
        params['table'] = "({}) data".format(manholes.query)
        datasource = mapnik.PostGIS(**params)

        # Define layer.

        layer = mapnik.Layer('manholeLayer')
        layer.datasource = datasource
        layer.maxzoom = 35000
        layer.styles.append('manholeStyle')

        layers.append(layer)
        styles['manholeStyle'] = style
Ejemplo n.º 14
0
    def addGeneralizedToMap(self, name='My New Style'):
        genColor = 'rgb(0%,0%,100%)'
        s = mapnik.Style()
        r = mapnik.Rule()
        if self.symbol_type == 'polygon':
            polygon_symbolizer = mapnik.PolygonSymbolizer(
                mapnik.Color(genColor))
            r.symbols.append(polygon_symbolizer)
        elif self.symbol_type == 'line':
            line_symbolizer = mapnik.LineSymbolizer(mapnik.Color(genColor), 2)
            r.symbols.append(line_symbolizer)
        else:
            print self.symbol_type, 'has to be implemented to preview!!!'
        s.rules.append(r)
        self.mapnik_map.append_style(name, s)

        lyr = mapnik.Layer('Generalized geometry from PostGIS')
        lyr.datasource = mapnik.PostGIS(
            host='localhost',
            user='******',
            password='******',
            dbname='meingis',
            table='(select geom from generalized_line_cache ) as water_ways')
        lyr.srs = self.layerSRS
        lyr.styles.append(name)
        self.mapnik_map.layers.append(lyr)
Ejemplo n.º 15
0
def generate_raster(filename, img_size, coordinates, background_color,
                    building_color, config_filename):
    """Generate a raster through requesting a PostGIS database with Mapnik

    Parameters
    ----------
    filename : str
        Output raster path on the file system
    img_size : int
        Size of the desired output image, in pixel (height=width)
    coordinates : dict
        Geographical coordinates of area of interest (west, south, east, north)
    and corresponding geographical projection (SRID)
    background_color : list of 3 ints
        Color of background pixels in [R,G,B]-format
    building_color : list of 3 ints
        Color of building pixels in [R,G,B]-format
    config_filename : str
        Path to the database connexion configuration file

    """
    mapnik_projection = get_mapnik_projection(coordinates["srid"])
    m = mapnik.Map(img_size, img_size, mapnik_projection)
    m.background = mapnik.Color(RGBToHTMLColor(background_color))
    s = mapnik.Style()
    r = mapnik.Rule()
    polygon_symbolizer = mapnik.PolygonSymbolizer()
    polygon_symbolizer.fill = mapnik.Color(RGBToHTMLColor(building_color))
    r.symbols.append(polygon_symbolizer)
    s.rules.append(r)
    m.append_style('building_style', s)

    place_name = filename_sanity_check(filename.split("/")[-1].split(".")[0])
    subquery = ("(SELECT way "
                "FROM {place}_polygon WHERE building='yes') AS building"
                "").format(place=place_name)
    conn_dict = read_config(config_filename)
    postgis_params = {
        'host': conn_dict["host"],
        'port': conn_dict["port"],
        'user': conn_dict["user"],
        'dbname': conn_dict["dbname"],
        'table': subquery,
        'geometry_field': "way",
        'srid': coordinates["srid"],
        'extent_from_subquery': True
    }
    ds = mapnik.PostGIS(**postgis_params)

    layer = mapnik.Layer('buildings')
    layer.datasource = ds
    layer.srs = mapnik_projection
    layer.styles.append('building_style')
    m.layers.append(layer)

    m.zoom_to_box(
        mapnik.Box2d(coordinates['west'], coordinates['south'],
                     coordinates['east'], coordinates['north']))
    mapnik.render_to_file(m, filename, 'tif')
Ejemplo n.º 16
0
 def test_variable_in_subquery1():
     ds = mapnik.PostGIS(dbname=MAPNIK_TEST_DBNAME,table='''
        (select * from test where @zoom = 30 ) as tmp''',
                         geometry_field='geom',
                         autodetect_key_field=True)
     fs = ds.featureset(variables={'zoom':30})
     for id in range(1,5):
         eq_(fs.next().id(),id)
Ejemplo n.º 17
0
 def test_bbox_token_in_subquery2():
     ds = mapnik.PostGIS(dbname=MAPNIK_TEST_DBNAME,table='''
        (SeLeCt * FrOm "tableWithMixedCase" where ST_Intersects(geom,!bbox!) ) as MixedCaseQuery''',
                         geometry_field='geom',
                         autodetect_key_field=True)
     fs = ds.featureset()
     for id in range(1,5):
         eq_(fs.next().id(),id)
Ejemplo n.º 18
0
 def create_ds_and_error():
     try:
         ds = mapnik.PostGIS(dbname=MAPNIK_TEST_DBNAME,
                             table='asdfasdfasdfasdfasdf',
                             max_size=20)
         fs = ds.all_features()
     except Exception, e:
         eq_('in executeQuery' in str(e), True)
Ejemplo n.º 19
0
def tms(z, x, y, service):
    # (4370311.220000, 4911352.860000) - (4403732.650000, 4958349.910000)
    # Extent: (4370177.610000, 4908530.650000) - (4411390.670000, 4958581.500000)
    bbox = dict(minx=4370177, miny=4908530, maxx=4411390, maxy=4958581)

    step = max(bbox['maxx'] - bbox['minx'], bbox['maxy'] - bbox['miny']) / 2**z

    extents = dict()

    extents['tms'] = (bbox['minx'] + x * step, bbox['miny'] + y * step,
                      bbox['minx'] + (x + 1) * step,
                      bbox['miny'] + (y + 1) * step)

    extents['xyz'] = (bbox['minx'] + x * step, bbox['maxy'] - (y + 1) * step,
                      bbox['minx'] + (x + 1) * step, bbox['maxy'] - y * step)

    tile = dict(width=256, height=256)
    map = mapnik.Map(tile['width'], tile['height'])
    map.background = mapnik.Color('steelblue')
    mapnik.load_map(map, 'tile_server/style/styles.xml')
    layer = mapnik.Layer('point')
    ds = mapnik.PostGIS(host='127.0.0.1',
                        dbname='isogd_sevastopol',
                        user='******',
                        password='******',
                        table='tableapi.table_test_2_points_2')
    layer.datasource = ds
    pdb.set_trace()
    style = mapnik.Style()
    rule = mapnik.Rule()
    point_symbolizer = mapnik.PointSymbolizer()
    point_symbolizer.file = "/style/point_style.png"
    # pdb.set_trace()

    rule.symbols.append(point_symbolizer)
    style.rules.append(rule)
    map.append_style('My Style', style)

    map.zoom_all()
    mapnik.render_to_file(map, 'altay.png', 'png')

    box = mapnik.Box2d(*extents.get(service))
    # map.zoom_all()
    map.zoom_to_box(box)
    mapnik.render_to_file(map, 'world.png', 'png')
    im = mapnik.Image(map.width, map.height)
    mapnik.render(map, im)
    output = im.tostring('png')

    # box = mapnik.Box2d(*extents.get(service))
    # map.zoom_to_box(box)
    # mapnik.render_to_file(map, 'world.png', 'png')
    # im = mapnik.Image(map.width, map.height)
    # mapnik.render(map, im)
    # output = im.tostring('png')
    # # Передаём ответ клиенту
    return output
Ejemplo n.º 20
0
    def layer(self, layer_ids=None, request=None):
        """Return mapnik layers and styles."""
        layers = []
        styles = {}
        style = mapnik.Style()
        styles["riverlineadapterstyle"] = style

        if self.riverline_result.is_reference:
            range_method = self._reference_ranges
            level_field = 'level'
        else:
            range_method = self._ranges
            level_field = 'relative_level'
        for from_, to_, color in range_method():
            rule = mapnik.Rule()
            if from_ is None:
                rule.filter = mapnik.Filter("[value] < %s" % to_)
            elif to_ is None:
                rule.filter = mapnik.Filter("[value] > %s" % from_)
            else:
                rule.filter = mapnik.Filter("[value] > %s and [value] < %s" %
                                            (from_, to_))
            symbol = mapnik.LineSymbolizer(
                mapnik.Color(color[0], color[1], color[2]), 3)
            rule.symbols.append(symbol)
            style.rules.append(rule)

        # Catch all rule for unknown states:
        rule = mapnik.Rule()
        rule.set_else(True)
        symbol = mapnik.LineSymbolizer(mapnik.Color(100, 100, 100), 3)
        rule.symbols.append(symbol)
        style.rules.append(rule)

        query = """(
            select riverline.the_geom, row.%s as value
            from lizard_rijnmond_riverline riverline,
            lizard_rijnmond_riverlineresultdata row
            where riverline.verbose_code = row.location
            and row.riverline_result_id = %s
        ) as data""" % (level_field, self.riverline_result_id)
        logger.info(query)
        default_database = settings.DATABASES['default']
        datasource = mapnik.PostGIS(
            host=default_database['HOST'],
            user=default_database['USER'],
            password=default_database['PASSWORD'],
            dbname=default_database['NAME'],
            table=str(query),
        )

        layer = mapnik.Layer("Riverlines", coordinates.RD)
        layer.datasource = datasource
        layer.styles.append("riverlineadapterstyle")
        layers.append(layer)

        return layers, styles
Ejemplo n.º 21
0
 def getDatasource(self, table):
     return mapnik.PostGIS(
         host=self.config.get('PG', 'host'),
         user=self.config.get('PG', 'user') or None,
         password=self.config.get('PG', 'password') or None,
         dbname=self.config.get('PG', 'database'),
         max_async_connection=4,
         #estimate_extent = True,
         table=table)
Ejemplo n.º 22
0
    def renderArea(self, width, height, srs, xmin, ymin, xmax, ymax, zoom,
                   auth):
        """
        """
        start_time = time()

        #
        # Mapnik can behave strangely when run in threads, so place a lock on the instance.
        #
        if global_mapnik_lock.acquire():
            try:
                if self.mapnik is None:
                    self.mapnik = get_mapnikMap(self.mapfile)
                    logging.debug(
                        'TileStache.Mapnik.ImageProvider.renderArea() %.3f to load %s',
                        time() - start_time, self.mapfile)

                #hack to only objects user is authorised to see
                #NOTE: check if auth_column is set?
                for la in self.mapnik.layers:
                    query = """(SELECT * 
                                FROM {}
                                WHERE {} IN ({})
                               ) AS {}""".format(
                        self.table, self.auth_column,
                        ', '.join(str(i) for i in auth), self.table)
                    la.datasource = mapnik.PostGIS(
                        host=str(self.host),
                        geometry_field=str(self.geometry_field),
                        key_field=str(self.key_field),
                        user=str(self.user),
                        password=str(self.password),
                        dbname=str(self.dbname),
                        table=query)

                self.mapnik.width = width
                self.mapnik.height = height
                self.mapnik.zoom_to_box(Box2d(xmin, ymin, xmax, ymax))

                img = mapnik.Image(width, height)
                mapnik.render(self.mapnik, img)
            except:
                self.mapnik = None
                raise
            finally:
                # always release the lock
                global_mapnik_lock.release()

        img = Image.fromstring('RGBA', (width, height), img.tostring())

        logging.debug(
            'TileStache.Mapnik.ImageProvider.renderArea() %dx%d in %.3f from %s',
            width, height,
            time() - start_time, self.mapfile)

        return img
Ejemplo n.º 23
0
 def test_empty_db():
     ds = mapnik.PostGIS(dbname=MAPNIK_TEST_DBNAME, table='empty')
     fs = ds.featureset()
     feature = None
     try:
         feature = fs.next()
     except StopIteration:
         pass
     eq_(feature, None)
     eq_(ds.describe()['geometry_type'], None)
Ejemplo n.º 24
0
    def test_numeric_type_feature_id_field():
        ds = mapnik.PostGIS(dbname=MAPNIK_TEST_DBNAME,table='test5',
                            geometry_field='geom',
                            autodetect_key_field=False)
        fs = ds.featureset()
        eq_(fs.next()['manual_id'],-1)
        eq_(fs.next()['manual_id'],1)

        fs = ds.featureset()
        eq_(fs.next().id(),1)
        eq_(fs.next().id(),2)
Ejemplo n.º 25
0
 def test_that_nonexistant_query_field_throws(**kwargs):
     ds = mapnik.PostGIS(dbname=MAPNIK_TEST_DBNAME, table='empty')
     eq_(len(ds.fields()), 1)
     eq_(ds.fields(), ['key'])
     eq_(ds.field_types(), ['int'])
     query = mapnik.Query(ds.envelope())
     for fld in ds.fields():
         query.add_property_name(fld)
     # also add an invalid one, triggering throw
     query.add_property_name('bogus')
     fs = ds.features(query)
Ejemplo n.º 26
0
def render_tile(layer, z, x, y):
    """
    Render the tile using mapnik.
    """

    m = mapnik.Map(TILE_WIDTH, TILE_WIDTH)

    s = mapnik.Style()
    r = mapnik.Rule()

    #line_symbolizer = mapnik.PointSymbolizer()
    line_symbolizer = mapnik.PolygonSymbolizer()
    line_symbolizer.fill = mapnik.Color('yellow')
    line_symbolizer.fill_opacity = 0.7
    #line_symbolizer.allow_overlap = True
    #line_symbolizer.transform="scale(5,5)"
    r.symbols.append(line_symbolizer)

    label = mapnik.TextSymbolizer(mapnik.Expression('[nama]'),
                                  'DejaVu Sans Book', 24, mapnik.Color('red'))
    label.halo_radius = 1
    label.avoid_edges = False
    r.symbols.append(label)

    s.rules.append(r)

    m.append_style('My Style', s)

    # Initialize layer from PostGIS table
    ds = mapnik.PostGIS(**POSTGIS_TABLE)
    layer2 = mapnik.Layer(LAYER_NAME)
    layer2.datasource = ds
    layer2.styles.append('My Style')
    m.layers.append(layer2)

    m.zoom_all()

    # ds = mapnik.Shapefile(file='C:\Users\ICS\Documents\kuliah\gis\gis mapnik\pantai indonesia\IND_PNT_polyline.shp')
    # layer = mapnik.Layer(LAYER_NAME)
    # layer.datasource = ds
    # layer.styles.append('My Style')
    # m.layers.append(layer)
    # m.zoom_all()

    renderer = TiledMapRenderer(m)
    im = renderer.render_tile(z, x, y)

    # im = mapnik.Image(TILE_WIDTH, TILE_WIDTH)
    # mapnik.render(m, im, 13, 0, 0)
    # im.save('tmp/bla.png')
    # mapnik.render_to_file(m,'aaa.png', 'png')

    return im.tostring('png'), 200, {'Content-type': 'image/png'}
Ejemplo n.º 27
0
    def test_null_comparision2():
        ds = mapnik.PostGIS(dbname=MAPNIK_TEST_DBNAME,
                            table='test10',
                            geometry_field='geom')
        fs = ds.featureset()
        feat = fs.next()
        eq_(feat['gid'], 1)
        eq_(feat['bool_field'], True)
        eq_(mapnik.Expression("[bool_field] = 'name'").evaluate(feat), False)
        eq_(mapnik.Expression("[bool_field] = ''").evaluate(feat), False)
        eq_(mapnik.Expression("[bool_field] = null").evaluate(feat), False)
        eq_(mapnik.Expression("[bool_field] = true").evaluate(feat), True)
        eq_(mapnik.Expression("[bool_field] = false").evaluate(feat), False)
        eq_(mapnik.Expression("[bool_field] != 'name'").evaluate(feat), True)
        eq_(mapnik.Expression("[bool_field] != ''").evaluate(feat),
            True)  # in 2.1.x used to be False
        eq_(mapnik.Expression("[bool_field] != null").evaluate(feat),
            True)  # in 2.1.x used to be False
        eq_(mapnik.Expression("[bool_field] != true").evaluate(feat), False)
        eq_(mapnik.Expression("[bool_field] != false").evaluate(feat), True)

        feat = fs.next()
        eq_(feat['gid'], 2)
        eq_(feat['bool_field'], False)
        eq_(mapnik.Expression("[bool_field] = 'name'").evaluate(feat), False)
        eq_(mapnik.Expression("[bool_field] = ''").evaluate(feat), False)
        eq_(mapnik.Expression("[bool_field] = null").evaluate(feat), False)
        eq_(mapnik.Expression("[bool_field] = true").evaluate(feat), False)
        eq_(mapnik.Expression("[bool_field] = false").evaluate(feat), True)
        eq_(mapnik.Expression("[bool_field] != 'name'").evaluate(feat), True)
        eq_(mapnik.Expression("[bool_field] != ''").evaluate(feat), True)
        eq_(mapnik.Expression("[bool_field] != null").evaluate(feat),
            True)  # in 2.1.x used to be False
        eq_(mapnik.Expression("[bool_field] != true").evaluate(feat), True)
        eq_(mapnik.Expression("[bool_field] != false").evaluate(feat), False)

        feat = fs.next()
        eq_(feat['gid'], 3)
        eq_(feat['bool_field'], None)  # null
        eq_(mapnik.Expression("[bool_field] = 'name'").evaluate(feat), False)
        eq_(mapnik.Expression("[bool_field] = ''").evaluate(feat), False)
        eq_(mapnik.Expression("[bool_field] = null").evaluate(feat), True)
        eq_(mapnik.Expression("[bool_field] = true").evaluate(feat), False)
        eq_(mapnik.Expression("[bool_field] = false").evaluate(feat), False)
        eq_(mapnik.Expression("[bool_field] != 'name'").evaluate(feat),
            True)  # in 2.1.x used to be False
        # https://github.com/mapnik/mapnik/issues/1859
        eq_(mapnik.Expression("[bool_field] != ''").evaluate(feat), False)
        eq_(mapnik.Expression("[bool_field] != null").evaluate(feat), False)
        eq_(mapnik.Expression("[bool_field] != true").evaluate(feat),
            True)  # in 2.1.x used to be False
        eq_(mapnik.Expression("[bool_field] != false").evaluate(feat),
            True)  # in 2.1.x used to be False
Ejemplo n.º 28
0
 def addBoxToMap(self, name='bbox'):
     genColor = 'rgb(0%,0%,100%)'
     s = mapnik.Style()
     r = mapnik.Rule()
     line_symbolizer = mapnik.LineSymbolizer(mapnik.Color(genColor),10)
     r.symbols.append(line_symbolizer)
     s.rules.append(r)
     self.mapnik_map.append_style(name,s)
     
     lyr = mapnik.Layer('BBox')
     lyr.datasource = mapnik.PostGIS(host='localhost',user='******',password='******',dbname='meingis',table='(select geom from bbox ) as water_ways')
     lyr.srs = self.layerSRS
     lyr.styles.append(name)
     self.mapnik_map.layers.append(lyr)
Ejemplo n.º 29
0
 def as_mapnik_layer(self):
     lyr = mapnik.Layer(self.name)
     query = f"(select spatial.geometry as geometry, spatial.name as name from spatial join data on spatial.fid = data.fid and data.variable= '{self.name}') as world"
     lyr.datasource = mapnik.PostGIS(
         host=current_app.config["DB_HOST"],
         port=current_app.config["DB_PORT"],
         dbname=current_app.config["DB_DB"],
         user=current_app.config["DB_USER"],
         password=current_app.config["DB_PASSWORD"],
         table=query,
     )
     lyr.srs = self.projection
     lyr.queryable = self.is_queryable
     return lyr
Ejemplo n.º 30
0
    def test_geometry_detection():
        ds = mapnik.PostGIS(dbname=MAPNIK_TEST_DBNAME,table='test',
                            geometry_field='geom')
        eq_(ds.describe()['geometry_type'],mapnik.DataGeometryType.Collection)

        ds = mapnik.PostGIS(dbname=MAPNIK_TEST_DBNAME,table='test',
                            geometry_field='geom',
                            row_limit=1)
        eq_(ds.describe()['geometry_type'],mapnik.DataGeometryType.Point)

        ds = mapnik.PostGIS(dbname=MAPNIK_TEST_DBNAME,table='test',
                            geometry_field='geom',
                            row_limit=2)
        eq_(ds.describe()['geometry_type'],mapnik.DataGeometryType.Point)

        ds = mapnik.PostGIS(dbname=MAPNIK_TEST_DBNAME,table='test',
                            geometry_field='geom',
                            row_limit=3)
        eq_(ds.describe()['geometry_type'],mapnik.DataGeometryType.Point)

        ds = mapnik.PostGIS(dbname=MAPNIK_TEST_DBNAME,table='test',
                            geometry_field='geom',
                            row_limit=4)
        eq_(ds.describe()['geometry_type'],mapnik.DataGeometryType.Collection)