def test_that_coordinates_do_not_overflow_and_polygon_is_rendered():
    expected_color = mapnik.Color('white')
    ds = mapnik.MemoryDatasource()
    context = mapnik.Context()
    ds.add_feature(mapnik.Feature.from_geojson(json.dumps(geojson), context))
    s = mapnik.Style()
    r = mapnik.Rule()
    sym = mapnik.PolygonSymbolizer()
    sym.fill = expected_color
    sym.clip = False
    r.symbols.append(sym)
    s.rules.append(r)
    lyr = mapnik.Layer('Layer')
    lyr.datasource = ds
    lyr.styles.append('style')
    m = mapnik.Map(256, 256)
    m.background_color = mapnik.Color('black')
    m.append_style('style', s)
    m.layers.append(lyr)
    # 17/20864/45265.png
    m.zoom_to_box(
        mapnik.Box2d(-13658379.710221574, 6197514.253362091,
                     -13657768.213995293, 6198125.749588372))
    # works 15/5216/11316.png
    #m.zoom_to_box(mapnik.Box2d(-13658379.710221574,6195679.764683247,-13655933.72531645,6198125.749588372))
    im = mapnik.Image(256, 256)
    mapnik.render(m, im)
    eq_(im.get_pixel(128, 128), expected_color.packed())
def test_add_feature():
    md = mapnik.MemoryDatasource()
    eq_(md.num_features(), 0)
    context = mapnik.Context()
    context.push('foo')
    feature = mapnik.Feature(context, 1)
    feature['foo'] = 'bar'
    feature.add_geometries_from_wkt('POINT(2 3)')
    md.add_feature(feature)
    eq_(md.num_features(), 1)

    featureset = md.features_at_point(mapnik.Coord(2, 3))
    retrieved = []

    for feat in featureset:
        retrieved.append(feat)

    eq_(len(retrieved), 1)
    f = retrieved[0]
    eq_(f['foo'], 'bar')

    featureset = md.features_at_point(mapnik.Coord(20, 30))
    retrieved = []
    for feat in featureset:
        retrieved.append(feat)
    eq_(len(retrieved), 0)
def test_that_coordinates_do_not_overflow_and_polygon_is_rendered_csv():
    expected_color = mapnik.Color('white')
    projection = '+init=epsg:4326'
    ds = mapnik.MemoryDatasource()
    context = mapnik.Context()
    feat = mapnik.Feature.from_geojson(json.dumps(geojson), context)
    ds.add_feature(feat)
    geojson_string = "geojson\n'%s'" % json.dumps(geojson['geometry'])
    ds = mapnik.Datasource(**{'type': 'csv', 'inline': geojson_string})
    s = mapnik.Style()
    r = mapnik.Rule()
    sym = mapnik.PolygonSymbolizer()
    sym.fill = expected_color
    r.symbols.append(sym)
    s.rules.append(r)
    lyr = mapnik.Layer('Layer', projection)
    lyr.datasource = ds
    lyr.styles.append('style')
    m = mapnik.Map(256, 256, projection)
    m.background_color = mapnik.Color('green')
    m.append_style('style', s)
    m.layers.append(lyr)
    # 17/20864/45265.png
    m.zoom_to_box(
        mapnik.Box2d(-13658379.710221574, 6197514.253362091,
                     -13657768.213995293, 6198125.749588372))
    # works 15/5216/11316.png
    # m.zoom_to_box(mapnik.Box2d(-13658379.710221574,6195679.764683247,-13655933.72531645,6198125.749588372))
    im = mapnik.Image(256, 256)
    mapnik.render(m, im)
    eq_(im.get_pixel(128, 128), expected_color.packed())
Exemple #4
0
def _render(themap, filename, format):
    m = themap.get_base_map().make_map()
    ctx = mapnik.Context()

    symbol_layers = {}
    for symbol in themap.get_symbols():
        svgfile = '/tmp/%s.svg' % symbol.get_id()
        _generate_svg(svgfile, symbol)

        ps = mapnik.PointSymbolizer()
        ps.file = svgfile
        ps.allow_overlap = True
        ps.ignore_placement = True

        r = mapnik.Rule()
        r.symbols.append(ps)

        s = mapnik.Style()
        s.rules.append(r)

        m.append_style('symbol_' + symbol.get_id(), s)

    ix = 0
    for marker in themap.get_markers():
        f = mapnik.Feature.from_geojson(
            json.dumps({
                "type": "Feature",
                "geometry": {
                    "type":
                    "Point",
                    "coordinates": [
                        float(marker.get_longitude()),
                        float(marker.get_latitude())
                    ]
                }
            }), ctx)

        ds = mapnik.MemoryDatasource()
        symbol_layers[symbol.get_id()] = ds

        l = mapnik.Layer('layer_%s' % ix)
        ix += 1
        l.clear_label_cache = True
        l.datasource = ds
        l.styles.append('symbol_' + marker.get_symbol().get_id())

        m.layers.append(l)

        ds.add_feature(f)

    mapnik.render_to_file(m, filename, format)

    box = None
    if themap.has_legend() and themap.has_symbols() and format == 'png':
        used_symbols = [
            s for s in themap.get_symbols() if themap.is_symbol_used(s)
        ]
        box = _add_legend(filename, used_symbols)
    return box
Exemple #5
0
def test_render_points():
    if not mapnik.has_cairo(): return
    # create and populate point datasource (WGS84 lat-lon coordinates)
    ds = mapnik.MemoryDatasource()
    context = mapnik.Context()
    context.push('Name')
    f = mapnik.Feature(context, 1)
    f['Name'] = 'Westernmost Point'
    f.add_geometries_from_wkt('POINT (142.48 -38.38)')
    ds.add_feature(f)

    f = mapnik.Feature(context, 2)
    f['Name'] = 'Southernmost Point'
    f.add_geometries_from_wkt('POINT (143.10 -38.60)')
    ds.add_feature(f)

    # create layer/rule/style
    s = mapnik.Style()
    r = mapnik.Rule()
    symb = mapnik.PointSymbolizer()
    symb.allow_overlap = True
    r.symbols.append(symb)
    s.rules.append(r)
    lyr = mapnik.Layer('Places',
                       '+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs')
    lyr.datasource = ds
    lyr.styles.append('places_labels')
    # latlon bounding box corners
    ul_lonlat = mapnik.Coord(142.30, -38.20)
    lr_lonlat = mapnik.Coord(143.40, -38.80)
    # render for different projections
    projs = {
        'google':
        '+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0.0 +k=1.0 +units=m +nadgrids=@null +wktext +no_defs +over',
        'latlon': '+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs',
        'merc': '+proj=merc +datum=WGS84 +k=1.0 +units=m +over +no_defs',
        'utm': '+proj=utm +zone=54 +datum=WGS84'
    }
    for projdescr in projs.iterkeys():
        m = mapnik.Map(1000, 500, projs[projdescr])
        m.append_style('places_labels', s)
        m.layers.append(lyr)
        dest_proj = mapnik.Projection(projs[projdescr])
        src_proj = mapnik.Projection('+init=epsg:4326')
        tr = mapnik.ProjTransform(src_proj, dest_proj)
        m.zoom_to_box(tr.forward(mapnik.Box2d(ul_lonlat, lr_lonlat)))
        # Render to SVG so that it can be checked how many points are there with string comparison
        svg_file = os.path.join(tempfile.gettempdir(),
                                'mapnik-render-points-%s.svg' % projdescr)
        mapnik.render_to_file(m, svg_file)
        num_points_present = len(ds.all_features())
        svg = open(svg_file, 'r').read()
        num_points_rendered = svg.count('<image ')
        eq_(
            num_points_present, num_points_rendered,
            "Not all points were rendered (%d instead of %d) at projection %s"
            % (num_points_rendered, num_points_present, projdescr))
Exemple #6
0
def render_png(tile, _zoom, xml, overscan):
    """
    Render the tile as a .png

    TODO: Actually handling zoom levels.
    """
    # mapnik is installed in a non-standard way.
    # It confuses pylint.
    # pylint: disable=no-member,too-many-locals

    map_tile_size = TILE_SIZE + (overscan * 2)
    logger = get_logger()
    ctx = mapnik.Context()

    map_tile = mapnik.Map(map_tile_size, map_tile_size)
    # scale_denom = 1 << (BASE_ZOOM - int(zoom or 1))
    # scale_factor = scale_denom / map_tile.scale_denominator()
    # map_tile.zoom(scale_factor)  # Is overriden by zoom_to_box.

    mapnik.load_map_from_string(map_tile, xml)

    box_min = -overscan
    box_max = TILE_SIZE + overscan - 1
    map_tile.zoom_to_box(mapnik.Box2d(box_min, box_min, box_max, box_max))

    for (name, features) in tile.items():
        name = name.encode('ascii', 'ignore')
        source = mapnik.MemoryDatasource()
        map_layer = mapnik.Layer(name)
        map_layer.datasource = source

        for feature in features:
            feat = mapnik.Feature(ctx, 0)

            try:
                feat.geometry = mapnik.Geometry.from_wkb(feature)
            except RuntimeError:
                try:
                    wkt = mapnik.Geometry.from_wkb(feature).to_wkt()
                    logger.error('Invalid feature: %s', wkt)
                except RuntimeError:
                    logger.error('Corrupt feature: %s', feature.encode('hex'))

            source.add_feature(feat)

        map_layer.styles.append(name)
        map_tile.layers.append(map_layer)

    image = mapnik.Image(TILE_SIZE, TILE_SIZE)
    # tile, image, scale, offset_x, offset_y
    mapnik.render(map_tile, image, 1, overscan, overscan)

    return image.tostring('png')
Exemple #7
0
def rasterize_tile(args):
    # Check tile already exists.
    output_file = args.o.format(z=args.z, x=args.x, y=args.y)
    output_dir = os.path.dirname(output_file)
    if os.path.exists(output_file) and not args.u:
        print("{} already exists".format(output_file))
        return (0)

    # Check that the directory exists and is writable.
    if not os.path.exists(output_dir):
        try:
            os.makedirs(output_dir)
        except OSError:
            print("Creation of the directory %s failed" % output_dir)
            return (5)
        else:
            print("%s/ created" % output_dir)

    # Set up projections
    # spherical mercator (most common target map projection of osm data imported with osm2pgsql)
    merc = mapnik.Projection(
        '+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +no_defs +over'
    )

    m = mapnik.Map(args.pixels, args.pixels)
    m.srs = merc.params()
    m.background = mapnik.Color('#00000000')
    m.append_style('Curvature Lines', CurvatureLinesStyle(args.z).get_style())

    vector_tile = CurvatureVectorTile(args.i, args.z, args.x, args.y)
    ds = mapnik.MemoryDatasource()
    vector_tile.add_features_to_datasource(ds)
    layer = mapnik.Layer('curvature')
    layer.srs = merc.params()
    layer.datasource = ds
    layer.styles.append('Curvature Lines')
    m.layers.append(layer)

    # Set the output bounding-box to the tile bounds.
    # merc_bbox = mercantile.bounds(args.x, args.y, args.z)
    # bbox = mapnik.Box2d(merc_bbox.west, merc_bbox.south, merc_bbox.east, merc_bbox.north)
    bbox = mapnik.Box2d(0, 0, vector_tile.extent, vector_tile.extent)
    m.zoom_to_box(bbox)

    mapnik.render_to_file(m, output_file, args.f)
    print("%s written" % output_file)

    if args.v:
        sys.stderr.write("{mem:.1f}MB\n".format(
            mem=resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1048576))
        sys.stderr.flush()
    return (0)
Exemple #8
0
def test_render_with_detector():
    ds = mapnik.MemoryDatasource()
    context = mapnik.Context()
    geojson = '{ "type": "Feature", "geometry": { "type": "Point", "coordinates": [ 0, 0 ] } }'
    ds.add_feature(mapnik.Feature.from_geojson(geojson, context))
    s = mapnik.Style()
    r = mapnik.Rule()
    lyr = mapnik.Layer('point')
    lyr.datasource = ds
    lyr.styles.append('point')
    symb = mapnik.MarkersSymbolizer()
    symb.allow_overlap = False
    r.symbols.append(symb)
    s.rules.append(r)
    m = mapnik.Map(256, 256)
    m.append_style('point', s)
    m.layers.append(lyr)
    m.zoom_to_box(mapnik.Box2d(-180, -85, 180, 85))
    im = mapnik.Image(256, 256)
    mapnik.render(m, im)
    expected_file = './images/support/marker-in-center.png'
    actual_file = '/tmp/' + os.path.basename(expected_file)
    #im.save(expected_file,'png8')
    im.save(actual_file, 'png8')
    actual = mapnik.Image.open(expected_file)
    expected = mapnik.Image.open(expected_file)
    eq_(
        actual.tostring('png32'), expected.tostring('png32'),
        'failed comparing actual (%s) and expected (%s)' %
        (actual_file, expected_file))
    # now render will a collision detector that should
    # block out the placement of this point
    detector = mapnik.LabelCollisionDetector(m)
    eq_(detector.extent(), mapnik.Box2d(-0.0, -0.0, m.width, m.height))
    eq_(detector.extent(), mapnik.Box2d(-0.0, -0.0, 256.0, 256.0))
    eq_(detector.boxes(), [])
    detector.insert(detector.extent())
    eq_(detector.boxes(), [detector.extent()])
    im2 = mapnik.Image(256, 256)
    mapnik.render_with_detector(m, im2, detector)
    expected_file_collision = './images/support/marker-in-center-not-placed.png'
    #im2.save(expected_file_collision,'png8')
    actual_file = '/tmp/' + os.path.basename(expected_file_collision)
    im2.save(actual_file, 'png8')
        def render_image(self, extent, img_size, settings):
            # Выбираем объекты по экстенту
            feature_query = self.layer.feature_query()
            feature_query.intersects(box(*extent, srid=self.layer.srs_id))
            feature_query.geom()
            features = feature_query()

            ds = mapnik.MemoryDatasource()
            for (id, f) in enumerate(features):
                if mapnik.mapnik_version() < 200100:
                    feature = mapnik.Feature(id)
                else:
                    feature = mapnik.Feature(mapnik.Context(), id)
                feature.add_geometries_from_wkb(f.geom.wkb)
                ds.add_feature(feature)

            style_content = str(self.style_content)

            m = mapnik.Map(img_size[0], img_size[1])
            mapnik.load_map_from_string(m, style_content)
            m.zoom_to_box(mapnik.Box2d(*extent))

            layer = mapnik.Layer('main')
            layer.datasource = ds

            root = ET.fromstring(style_content)
            styles = [s.attrib.get('name') for s in root.iter('Style')]
            for s in styles:
                layer.styles.append(s)
            m.layers.append(layer)

            img = mapnik.Image(img_size[0], img_size[1])
            mapnik.render(m, img)
            data = img.tostring('png')

            # Преобразуем изображение из PNG в объект PIL
            buf = StringIO()
            buf.write(data)
            buf.seek(0)

            img = Image.open(buf)
            return img
Exemple #10
0
def make_tmp_map():
    m = mapnik.Map(512,512)
    m.background_color = mapnik.Color('steelblue')
    ds = mapnik.MemoryDatasource()
    context = mapnik.Context()
    context.push('Name')
    f = mapnik.Feature(context,1)
    f['Name'] = 'Hello'
    f.add_geometries_from_wkt('POINT (0 0)')
    ds.add_feature(f)
    s = mapnik.Style()
    r = mapnik.Rule()
    sym = mapnik.MarkersSymbolizer()
    sym.allow_overlap = True
    r.symbols.append(sym)
    s.rules.append(r)
    lyr = mapnik.Layer('Layer')
    lyr.datasource = ds
    lyr.styles.append('style')
    m.append_style('style',s)
    m.layers.append(lyr)
    return m
    def layer(self, layer_ids=None, request=None):
        """Return a layer with all stickies or stickies with selected
        tags
        """
        start_end = current_start_end_dates(request)
        layers = []
        styles = {}
        layer = mapnik.Layer("Stickies", WGS84)
        layer.datasource = mapnik.MemoryDatasource()
        stickies = self.stickies.exclude(time__gte=start_end[1]).filter(
            time__gte=start_end[0])
        for _id, sticky in enumerate(stickies):
            add_datasource_point(layer.datasource, sticky.geom.x,
                                 sticky.geom.y, 'Name', 'hssd', _id)
        # generate "unique" point style name and append to layer
        style_name = "StickyTweets"
        styles[style_name] = self.style()
        layer.styles.append(style_name)

        layers = [
            layer,
        ]
        return layers, styles
Exemple #12
0
def make_map():
    ds = mapnik.MemoryDatasource()
    context = mapnik.Context()
    context.push('Name')
    pixel_key = 1
    f = mapnik.Feature(context, pixel_key)
    f['Name'] = str(pixel_key)
    f.add_geometries_from_wkt('POLYGON ((0 0, 0 256, 256 256, 256 0, 0 0))')
    ds.add_feature(f)
    s = mapnik.Style()
    r = mapnik.Rule()
    symb = mapnik.PolygonSymbolizer()
    r.symbols.append(symb)
    s.rules.append(r)
    lyr = mapnik.Layer('Places')
    lyr.datasource = ds
    lyr.styles.append('places_labels')
    width, height = 256, 256
    m = mapnik.Map(width, height)
    m.append_style('places_labels', s)
    m.layers.append(lyr)
    m.zoom_all()
    return m
Exemple #13
0
    def test_render_layer_to_cairo_context():
        ds = mapnik.MemoryDatasource()
        context = mapnik.Context()
        context.push('Name')
        f = mapnik.Feature(context, 1)
        f['Name'] = 'poly'
        f.geometry = mapnik.Geometry.from_wkt(
            'POLYGON ((1 1, -1 1, -1 -1, 1 -1, 1 1))')
        ds.add_feature(f)
        s = mapnik.Style()
        r = mapnik.Rule()
        symb = mapnik.PolygonSymbolizer()
        symb.fill = mapnik.Color('red')
        r.symbols.append(symb)
        s.rules.append(r)
        lyr = mapnik.Layer('poly')
        lyr.datasource = ds
        lyr.styles.append('poly')
        m = mapnik.Map(256, 256)
        m.append_style('poly', s)
        m.layers.append(lyr)
        m.zoom_all()

        surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, m.width, m.height)
        context = cairo.Context(surface)
        detector = mapnik.LabelCollisionDetector(m)
        mapnik.render_layer(m, context, detector, lyr)

        im = mapnik.Image.from_cairo(surface)

        eq_(im.is_solid(), True)
        c = im.get_pixel(0, 0, True)
        eq_(c.r, 255)
        eq_(c.g, 0)
        eq_(c.b, 0)
        eq_(c.a, 255)
Exemple #14
0
 def gen_grid_for_id(pixel_key):
     ds = mapnik.MemoryDatasource()
     context = mapnik.Context()
     context.push('Name')
     f = mapnik.Feature(context,pixel_key)
     f['Name'] = str(pixel_key)
     f.add_geometries_from_wkt('POLYGON ((0 0, 0 256, 256 256, 256 0, 0 0))')
     ds.add_feature(f)
     s = mapnik.Style()
     r = mapnik.Rule()
     symb = mapnik.PolygonSymbolizer()
     r.symbols.append(symb)
     s.rules.append(r)
     lyr = mapnik.Layer('Places')
     lyr.datasource = ds
     lyr.styles.append('places_labels')
     width,height = 256,256
     m = mapnik.Map(width,height)
     m.append_style('places_labels',s)
     m.layers.append(lyr)
     m.zoom_all()
     grid = mapnik.Grid(m.width,m.height,key='__id__')
     mapnik.render_layer(m,grid,layer=0,fields=['__id__','Name'])
     return grid
def generateMap(tableName,
                minX,
                minY,
                maxX,
                maxY,
                mapWidth,
                mapHeight,
                hiliteExpr=None,
                points=None):

    extent = "{},{},{},{}".format(minX, minY, maxX, maxY)

    layer = mapnik.Layer("Layer")
    layer.datasource = mapnik.PostGIS(dbname="distal",
                                      table=tableName,
                                      user="******",
                                      password="******",
                                      extent=extent,
                                      geometry_field="outline",
                                      srid=4326)

    map = mapnik.Map(mapWidth, mapHeight, '+proj=longlat +datum=WGS84')
    map.background = mapnik.Color("#8080a0")

    style = mapnik.Style()

    rule = mapnik.Rule()
    if hiliteExpr != None:
        rule.filter = mapnik.Filter(hiliteExpr)

    rule.symbols.append(mapnik.PolygonSymbolizer(mapnik.Color("#408000")))
    rule.symbols.append(
        mapnik.LineSymbolizer(mapnik.Stroke(mapnik.Color("#000000"), 0.1)))

    style.rules.append(rule)

    rule = mapnik.Rule()
    rule.set_else(True)

    rule.symbols.append(mapnik.PolygonSymbolizer(mapnik.Color("#a0a0a0")))
    rule.symbols.append(
        mapnik.LineSymbolizer(mapnik.Stroke(mapnik.Color("#404040"), 0.1)))

    style.rules.append(rule)

    map.append_style("Map Style", style)
    layer.styles.append("Map Style")
    map.layers.append(layer)

    if points != None:
        memoryDatasource = mapnik.MemoryDatasource()
        context = mapnik.Context()
        context.push("name")
        next_id = 1
        for long, lat, name in points:
            wkt = "POINT (%0.8f %0.8f)" % (long, lat)
            feature = mapnik.Feature(context, next_id)
            feature['name'] = name
            feature.add_geometries_from_wkt(wkt)
            next_id = next_id + 1
            memoryDatasource.add_feature(feature)

        layer = mapnik.Layer("Points")
        layer.datasource = memoryDatasource

        style = mapnik.Style()
        rule = mapnik.Rule()

        pointImgFile = os.path.join(os.path.dirname(__file__), "point.png")

        shield = mapnik.ShieldSymbolizer(mapnik.Expression('[name]'),
                                         "DejaVu Sans Bold", 10,
                                         mapnik.Color("#000000"),
                                         mapnik.PathExpression(pointImgFile))
        shield.displacement = (0, 7)
        shield.unlock_image = True
        rule.symbols.append(shield)

        style.rules.append(rule)

        map.append_style("Point Style", style)
        layer.styles.append("Point Style")

        map.layers.append(layer)

    map.zoom_to_box(mapnik.Envelope(minX, minY, maxX, maxY))

    scriptDir = os.path.dirname(__file__)
    cacheDir = os.path.join(scriptDir, "..", "mapCache")
    if not os.path.exists(cacheDir):
        os.mkdir(cacheDir)
    fd, filename = tempfile.mkstemp(".png", dir=cacheDir)
    os.close(fd)

    mapnik.render_to_file(map, filename, "png")

    return "../mapCache/" + os.path.basename(filename)
    imgy = 1000 * z

    m = mapnik.Map(imgx, imgy)
    mapnik.load_map(m, mapfile)
    # ensure the target map projection is mercator
    m.srs = merc.params()

    s = mapnik.Style()  # style object to hold rules
    r = mapnik.Rule()  # rule object to hold symbolizers
    point_sym = mapnik.PointSymbolizer()
    point_sym.filename = './symbols/airport.p.16.png'
    r.symbols.append(point_sym)  # add the symbolizer to the rule object
    s.rules.append(r)  # now add the rule to the style and we're done
    m.append_style('airport point', s)

    ds = mapnik.MemoryDatasource()
    f = mapnik.Feature(mapnik.Context(), 1)
    f.add_geometries_from_wkt("POINT(-92.289595 34.746481)")
    ds.add_feature(f)

    player = mapnik.Layer('airport_layer')
    player.srs = longlat.params()
    player.datasource = ds
    player.styles.append('airport point')
    m.layers.append(player)
    m.zoom_all()

    if hasattr(mapnik, 'Box2d'):
        bbox = mapnik.Box2d(*bounds)
    else:
        bbox = mapnik.Envelope(*bounds)
Exemple #17
0
def test_render_grid():
    ds = mapnik.MemoryDatasource()
    context = mapnik.Context()
    context.push('Name')
    f = mapnik.Feature(context,1)
    f['Name'] = 'South East'
    f.add_geometries_from_wkt('POINT (143.10 -38.60)')
    ds.add_feature(f)

    f = mapnik.Feature(context,2)
    f['Name'] = 'South West'
    f.add_geometries_from_wkt('POINT (142.48 -38.60)')
    ds.add_feature(f)

    f = mapnik.Feature(context,3)
    f['Name'] = 'North West'
    f.add_geometries_from_wkt('POINT (142.48 -38.38)')
    ds.add_feature(f)

    f = mapnik.Feature(context,4)
    f['Name'] = 'North East'
    f.add_geometries_from_wkt('POINT (143.10 -38.38)')
    ds.add_feature(f)

    s = mapnik.Style()
    r = mapnik.Rule()
    symb = mapnik.MarkersSymbolizer()
    symb.width = 10
    symb.height = 10
    symb.allow_overlap = True
    r.symbols.append(symb)
    s.rules.append(r)
    lyr = mapnik.Layer('Places')
    lyr.datasource = ds
    lyr.styles.append('places_labels')
    m = mapnik.Map(256,256)
    m.append_style('places_labels',s)
    m.layers.append(lyr)
    ul_lonlat = mapnik.Coord(142.30,-38.20)
    lr_lonlat = mapnik.Coord(143.40,-38.80)
    m.zoom_to_box(mapnik.Box2d(ul_lonlat,lr_lonlat))
    grid = mapnik.render_grid(m,0,key='Name',resolution=4,fields=['Name'])
    eq_(grid,grid_correct)
    eq_(resolve(grid,0,0),None)

    # check every pixel of the nw symbol
    expected = {"Name": "North West"}

    # top row
    eq_(resolve(grid,23,9),expected)
    eq_(resolve(grid,23,10),expected)
    eq_(resolve(grid,23,11),expected)

    # core
    eq_(resolve(grid,24,8),expected)
    eq_(resolve(grid,24,9),expected)
    eq_(resolve(grid,24,10),expected)
    eq_(resolve(grid,24,11),expected)
    eq_(resolve(grid,24,12),expected)
    eq_(resolve(grid,25,8),expected)
    eq_(resolve(grid,25,9),expected)
    eq_(resolve(grid,25,10),expected)
    eq_(resolve(grid,25,11),expected)
    eq_(resolve(grid,25,12),expected)

    # bottom row
    eq_(resolve(grid,26,9),expected)
    eq_(resolve(grid,26,10),expected)
    eq_(resolve(grid,26,11),expected)
Exemple #18
0
def service_get_wms_of_shape(request, width, height, bbox,
                             presentationlayer_id, legend_id, timestep):
    """
    width = int
    height = int
    bbox = tuple
    """
    pl = get_object_or_404(PresentationLayer, pk=presentationlayer_id)
    if legend_id == -1:
        legend_id = pl.presentationtype.default_legend_id

    #presentation_dir = Setting.objects.get( key = 'presentation_dir' ).value

    #################### set up map ###################################
    log.debug('start setting up map ' + str(datetime.datetime.now()))

    m = mapnik.Map(width, height)
    spherical_mercator = (
        '+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 '
        '+y_0=0 +k=1.0 +units=m +nadgrids=@null +no_defs +over')

    m.srs = spherical_mercator
    m.background = mapnik.Color('transparent')
    #p = mapnik.Projection(spherical_mercator)

    log.debug('start setting up legend ' + str(datetime.datetime.now()))
    #################### set up legend ###################################

    mpl = cache.get('legend_' + str(legend_id))
    if mpl == None:
        sdl = get_object_or_404(ShapeDataLegend, pk=legend_id)
        if pl.presentationtype.geo_type in [
                PresentationType.GEO_TYPE_POLYGON,
                PresentationType.GEO_TYPE_LINE, PresentationType.GEO_TYPE_POINT
        ]:
            sm = SymbolManager('media/flooding_presentation/symbols/')
            mpl = MapnikPointLegend(sdl, sm)
            cache.set('legend_' + str(legend_id), mpl, 300)

    fields = mpl.get_presentationtype_fields()

    log.debug('start setting up lijntje ' + str(datetime.datetime.now()))
    #################### supportive layers ###################################
    if SupportLayers.objects.filter(
            presentationtype=pl.presentationtype).count() > 0:
        supportive_layers = (pl.presentationtype.supported_presentationtype.
                             supportive_presentationtype.all())

        sl = mapnik.Style()
        rule_l = mapnik.Rule()

        rule_stk = mapnik.Stroke()
        rule_stk.color = mapnik.Color(3, 158, 137)
        rule_stk.line_cap = mapnik.line_cap.ROUND_CAP
        rule_stk.width = 2.0
        rule_l.symbols.append(mapnik.LineSymbolizer(rule_stk))
        sl.rules.append(rule_l)
        m.append_style('Line Style', sl)

        for spt in supportive_layers:
            log.debug('supportive layer with id: ' + str(spt.id))

            # warning! works only for flooding scenarios
            if pl.scenario_set.count() > 0:
                scenario = pl.scenario_set.get()
                layers = PresentationLayer.objects.filter(presentationtype=spt,
                                                          scenario=scenario)

                if len(layers) > 0:
                    log.debug(
                        'supportive layer found for this presentationlayer')
                    layer = layers[0]

                    lyrl = mapnik.Layer('lines', spherical_mercator)
                    lyrl.datasource = mapnik.Shapefile(
                        file=external_file_location(
                            layer.presentationshape.geo_source.file_location))

                    lyrl.styles.append('Line Style')
                    m.layers.append(lyrl)

    #################### read data ###################################
    #read source and attach values
    log.debug('ready setting up map ' + str(datetime.datetime.now()))
    log.debug('start reading point cache ' + str(datetime.datetime.now()))
    points = cache.get('model_nodes_' + str(presentationlayer_id) + '_' +
                       str(timestep) + '_' + str(legend_id))
    log.debug('ready reading point cache ' + str(datetime.datetime.now()))

    if points is None:
        log.debug('start reading points from shape and his file ' +
                  str(datetime.datetime.now()))
        points = []

        drv = ogr.GetDriverByName('ESRI Shapefile')
        shapefile_name = external_file_location(
            pl.presentationshape.geo_source.file_location)
        ds = drv.Open(shapefile_name)
        layer = ds.GetLayer()

        has_his_file_field = False
        has_geo_file_field = False
        geo_fields = []
        log.debug('fields are: ' + str(fields))
        for nr in fields:
            field = fields[nr]
            if field.source_type == Field.SOURCE_TYPE_VALUE_SOURCE_PARAM:
                has_his_file_field = True
                his_field = field
                #only his files yet supported. read needed data
                log.debug('start reading hiscache' +
                          str(datetime.datetime.now()))
                his = cache.get('his_' + str(presentationlayer_id))
                log.debug('ready reading hiscache' +
                          str(datetime.datetime.now()))

                if his == None:
                    log.debug('read hisfile' + str(datetime.datetime.now()))
                    zip_name = external_file_location(
                        pl.presentationshape.value_source.file_location)
                    input_file = ZipFile(zip_name, "r")
                    if pl.presentationtype.geo_source_filter:
                        filename = pl.presentationtype.geo_source_filter
                    else:
                        filename = input_file.filelist[0].filename

                    his = HISFile(Stream(input_file.read(filename)))
                    input_file.close()
                    log.debug('ready reading hisfile' +
                              str(datetime.datetime.now()))
                    cache.set('his_' + str(presentationlayer_id), his, 3000)

                values = his.get_values_timestep_by_index(
                    his.get_parameter_index(his_field.name_in_source),
                    timestep)

            elif field.source_type == Field.SOURCE_TYPE_GEO_SOURCE_COL:
                has_geo_file_field = True
                geo_fields.append(field)
            else:
                log.debug('field source type ' + field.source_type +
                          ' not yet supported')

        if (layer.GetFeatureCount() > 0):
            feature = layer.next()
            id_index = feature.GetFieldIndex('id')

            for field in geo_fields:
                field.index_nr = feature.GetFieldIndex(
                    str(field.name_in_source))

            layer.ResetReading()
        ############################# place features in the right 'legend box'

        for feature in layer:
            point = feature.geometry()

            input_dict = {}

            if has_his_file_field:
                #get id form geosource, needed for reading hisfile
                id = (pl.presentationtype.value_source_id_prefix +
                      str(feature.GetField(id_index).strip()))
                if pl.presentationtype.absolute:
                    try:
                        input_dict[his_field.name_in_source] = abs(
                            values.get(id, None))
                        if values.get(id, None) > 1:
                            pass

                    except TypeError:
                        input_dict[his_field.name_in_source] = None
                else:
                    input_dict[his_field.name_in_source] = values.get(id, None)

            if has_geo_file_field:
                for field in geo_fields:
                    input_dict[field.name_in_source] = feature.GetField(
                        field.index_nr)

            rule_name = mpl.get_rule_name(input_dict)

            if pl.presentationtype.geo_type == 3:
                x = (point.GetX(0) + point.GetX(1)) / 2
                y = (point.GetY(0) + point.GetY(1)) / 2
            else:
                x = point.GetX()
                y = point.GetY()

            #rule_name = str('1_neerslag_64_0010000100_24x24_0_0')
            points.append((x, y, "NAME", rule_name))
    # Clean up
        ds.Destroy()
        log.debug('ready reading points form shape en his file ' +
                  str(datetime.datetime.now()))

        cache.set(
            'model_nodes_' + str(presentationlayer_id) + '_' + str(timestep) +
            '_' + str(legend_id), points, 300)

    log.debug('start making memory datasource ' + str(datetime.datetime.now()))

    lyr = mapnik.Layer('Points', spherical_mercator)
    m.append_style('Points legend', mpl.get_style())

    memory_ds = mapnik.MemoryDatasource()  #lyr.datasource
    context = mapnik.Context()
    context.push("name")
    next_id = 1
    for x, y, name, rule_name in points:
        wkt = "POINT(%0.1f %0.1f)" % (x, y)
        feature = mapnik.Feature(context, next_id)
        feature[name] = rule_name
        feature.add_geometries_from_wkt(wkt)
        memory_ds.add_feature(feature)
        next_id += 1
    lyr.datasource = memory_ds
    log.debug('finish making memory datasource ' +
              str(datetime.datetime.now()))
    lyr.styles.append('Points legend')
    m.layers.append(lyr)

    if presentationlayer_id in [62007, 62008]:
        m = mapnik.Map(width, height)
        spherical_mercator = mapnik.Projection(
            '+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 '
            '+y_0=0 +k=1.0 +units=m +nadgrids=@null +no_defs +over')

        m.srs = spherical_mercator
        m.background = mapnik.Color('transparent')

        sl = mapnik.Style()
        rule_l = mapnik.Rule()

        rule_stk = mapnik.Stroke()
        rule_stk.color = mapnik.Color(3, 158, 137)
        rule_stk.line_cap = mapnik.line_cap.ROUND_CAP
        rule_stk.width = 2.0
        rule_l.symbols.append(mapnik.LineSymbolizer(rule_stk))
        sl.rules.append(rule_l)
        m.append_style('Line Style2', sl)

        scenario = pl.scenario_set.get()
        layers = PresentationLayer.objects.filter(presentationtype=spt,
                                                  scenario=scenario)
        log.debug('supportive layer found for this presentationlayer')

        rds = mapnik.Projection(
            "+proj=sterea +lat_0=52.15616055555555 +lon_0=5.38763888888889 "
            "+k=0.999908 +x_0=155000 +y_0=463000 +ellps=bessel "
            "+towgs84=565.237,50.0087,465.658,-0.406857,0.350733,"
            "-1.87035,4.0812 +units=m +no_defs")
        lyrl = mapnik.Layer('lines', rds)
        # Commented out, variable 'presentation_dir' doesn't exist so this
        # cannot work. -- RG20120621
        #        lyrl.datasource = mapnik.Shapefile(
        #            file=external_file_location(
        #                str(presentation_dir + '\\' +
        #                    pl.presentationshape.geo_source.file_location)))
        lyrl.styles.append('Line Style2')
        m.layers.append(lyrl)

    ##################### render map #############################
    m.zoom_to_box(mapnik.Envelope(*bbox))  # lyrl.envelope

    log.debug('start render map ' + str(datetime.datetime.now()))
    img = mapnik.Image(width, height)
    mapnik.render(m, img)
    log.debug('ready render map ' + str(datetime.datetime.now()))

    log.debug('start PIL ' + str(datetime.datetime.now()))
    # you can use this if you want te modify image with PIL
    imgPIL = Image.fromstring('RGBA', (width, height), img.tostring())
    #imgPIL = imgPIL.convert('RGB')
    buffer = StringIO.StringIO()
    imgPIL.save(buffer, 'png')  # ,transparency = 10
    buffer.seek(0)

    response = HttpResponse(buffer.read())
    log.debug('end PIL ' + str(datetime.datetime.now()))
    response['Content-type'] = 'image/png'
    log.debug('ready sending map ' + str(datetime.datetime.now()))
    return response