Beispiel #1
0
    def render_tile(self, tile_uri, x, y, z):

        # Calculate pixel positions of bottom-left & top-right
        p0 = (x * 256, (y + 1) * 256)
        p1 = ((x + 1) * 256, y * 256)

        # Convert to LatLong (EPSG:4326)
        l0 = self.tileproj.fromPixelToLL(p0, z)
        l1 = self.tileproj.fromPixelToLL(p1, z)

        # Convert to map projection (e.g. mercator co-ords EPSG:900913)
        c0 = self.prj.forward(mapnik.Coord(l0[0], l0[1]))
        c1 = self.prj.forward(mapnik.Coord(l1[0], l1[1]))

        # Bounding box for the tile
        if hasattr(mapnik,
                   'mapnik_version') and mapnik.mapnik_version() >= 800:
            bbox = mapnik.Box2d(c0.x, c0.y, c1.x, c1.y)
        else:
            bbox = mapnik.Envelope(c0.x, c0.y, c1.x, c1.y)
        render_size = 256
        self.m.resize(render_size, render_size)
        self.m.zoom_to_box(bbox)
        if (self.m.buffer_size < 128):
            self.m.buffer_size = 128

        # Render image with default Agg renderer
        im = mapnik.Image(render_size, render_size)
        mapnik.render(self.m, im)
        im.save(tile_uri, 'png256')
Beispiel #2
0
def test_wgs84_inverse_forward():
    p = mapnik2.Projection('+init=epsg:4326')

    c = mapnik2.Coord(3.01331418311, 43.3333092669)
    e = mapnik2.Box2d(-122.54345245, 45.12312553, 68.2335581353, 48.231231233)

    # It appears that the y component changes very slightly, is this OK?
    # so we test for 'almost equal float values'
    
    assert_almost_equal(p.inverse(c).y, c.y)
    assert_almost_equal(p.inverse(c).x, c.x)

    assert_almost_equal(p.forward(c).y, c.y)
    assert_almost_equal(p.forward(c).x, c.x)

    assert_almost_equal(p.inverse(e).center().y, e.center().y)
    assert_almost_equal(p.inverse(e).center().x, e.center().x)

    assert_almost_equal(p.forward(e).center().y, e.center().y)
    assert_almost_equal(p.forward(e).center().x, e.center().x)

    assert_almost_equal(c.inverse(p).y, c.y)
    assert_almost_equal(c.inverse(p).x, c.x)

    assert_almost_equal(c.forward(p).y, c.y)
    assert_almost_equal(c.forward(p).x, c.x)

    assert_almost_equal(e.inverse(p).center().y, e.center().y)
    assert_almost_equal(e.inverse(p).center().x, e.center().x)

    assert_almost_equal(e.forward(p).center().y, e.center().y)
    assert_almost_equal(e.forward(p).center().x, e.center().x)
Beispiel #3
0
    def renderTile(self, width, height, srs, coord):
        """
        """
        if self.mapnik is None:
            self.mapnik = mapnik.Map(0, 0)
            mapnik.load_map(self.mapnik, str(self.mapfile))

        nw = self.layer.projection.coordinateLocation(coord)
        se = self.layer.projection.coordinateLocation(coord.right().down())
        ul = self.mercator.locationProj(nw)
        lr = self.mercator.locationProj(se)

        self.mapnik.width = width
        self.mapnik.height = height
        self.mapnik.zoom_to_box(mapnik.Box2d(ul.x, ul.y, lr.x, lr.y))

        # create grid as same size as map/image
        grid = mapnik.Grid(width, height)
        # render a layer to that grid array
        mapnik.render_layer(self.mapnik,
                            grid,
                            layer=self.layer_index,
                            fields=self.fields)
        # then encode the grid array as utf, resample to 1/scale the size, and dump features
        grid_utf = grid.encode('utf', resolution=self.scale, features=True)

        if self.wrapper is None:
            return SaveableResponse(json.dumps(grid_utf))
        else:
            return SaveableResponse(self.wrapper + '(' + json.dumps(grid_utf) +
                                    ')')
Beispiel #4
0
    def get_one(self, tile: Tile) -> Optional[Tile]:
        bbox = self.tilegrid.extent(tile.tilecoord, self.buffer)
        bbox2d = mapnik.Box2d(bbox[0], bbox[1], bbox[2], bbox[3])

        size = tile.tilecoord.n * self.tilegrid.tile_size + 2 * self.buffer
        self.mapnik.resize(size, size)
        self.mapnik.zoom_to_box(bbox2d)

        if self.output_format == "grid":
            grid = mapnik.Grid(self.tilegrid.tile_size,
                               self.tilegrid.tile_size)
            for n, l in enumerate(self.mapnik.layers):
                if l.name in self.layers_fields:
                    mapnik.render_layer(self.mapnik,
                                        grid,
                                        layer=n,
                                        fields=self.layers_fields[l.name])

            encode = grid.encode("utf", resolution=self.resolution)
            if self.drop_empty_utfgrid and len(encode["data"].keys()) == 0:
                return None
            tile.data = dumps(encode).encode()
        else:
            # Render image with default Agg renderer
            im = mapnik.Image(size, size)
            mapnik.render(self.mapnik, im)
            tile.data = im.tostring(self.output_format)

        return tile
Beispiel #5
0
    def rpc_renderArea(self, minlat, minlon, maxlat, maxlon):
        """
        Renders a map for the given coordin
        """
        Map = None

        LandmassShapefile = 'cape/Interface/ne_110m_admin_0_countries.shp'

        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')

        # long/lat in degrees, aka ESPG:4326 and "WGS 84"
        longlat = mapnik.Projection(
            '+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs')
        # can also be constructed as:
        #longlat = mapnik.Projection('+init=epsg:4326')

        im = mapnik.Image(self.mapsize)

        m = self.rendermap
        m.srs = merc.params()
        bbox = mapnik.Box2d(minlat, minlon, maxlat, maxlon)
        transform = mapnik.ProjTransform(longlat, merc)
        merc_bbox = transform.forward(bbox)

        m.zoom_to_box(merc_bbox)
        mapnik.render(m, im)
        Map = im.tostring('png')

        return (True, Map)
Beispiel #6
0
 def render_location(self):
     # 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')
     longlat = mapnik.Projection('+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs')
     mapfile = "renderer/map_data/styles/bs_complete.xml"
     bounds = (self.lon-self.size, self.lat-self.size, self.lon+self.size,self.lat+self.size)
     z = 1
     imgx = 224 * z
     imgy = 224 * z
     m = mapnik.Map(imgx,imgy)
     mapnik.load_map(m,mapfile)
     m.srs = merc.params()
     if hasattr(mapnik,'Box2d'):
         bbox = mapnik.Box2d(*bounds)
     else:
         bbox = mapnik.Envelope(*bounds)
     transform = mapnik.ProjTransform(longlat,merc)
     merc_bbox = transform.forward(bbox)
     m.zoom_to_box(merc_bbox)
     #render the map to an image
     im = mapnik.Image(imgx,imgy)
     mapnik.render(m, im)
     img = im.tostring('png256')
     img = cv2.imdecode(np.fromstring(img, dtype=np.uint8), 1)
     img =np.asarray(img)
     window_name = "Location"
     cv2.imshow(window_name, img)
     cv2.waitKey(0)
Beispiel #7
0
    def rendertiles(self, bounds, data, item, label, lat, layer, lon,
                    num_items, projec):
        z = 1
        imgx = 128 * z
        imgy = 128 * z

        mapfile = "/map_data/styles/bs_" + layer + ".xml"

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

        if hasattr(mapnik, 'Box2d'):
            bbox = mapnik.Box2d(*bounds)
        else:
            bbox = mapnik.Envelope(*bounds)

        transform = mapnik.ProjTransform(longlat, projec)
        merc_bbox = transform.forward(bbox)

        m.zoom_to_box(merc_bbox)

        # render the map to an image
        im = mapnik.Image(imgx, imgy)
        mapnik.render(m, im)
        img = im.tostring('png256')
        data[(item, layer)] = img
Beispiel #8
0
    def render_location_with_variants(self, variants):
               # target projection
        #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')
        data = []
        for item in range(0,variants):
            if item == 0:
                teta = 0
                zoom = 20
                shift_lat = 0
                shift_lon = 0
            else:
                shift_lat = 0.1*self.size*(random.random()-random.random()) 
                shift_lon = 0.1*self.size*(random.random()-random.random())
                teta = 45 * (random.random()-random.random())
                zoom = random.randint(17,21)

            layer = "complete"
            projec = mapnik.Projection('+proj=aeqd +ellps=WGS84 +lat_0=90 +lon_0='+str(teta))        
            # WGS lat/long source projection of centre
            longlat = mapnik.Projection('+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs')
            
            # make a new Map object for the given mapfile
            m = mapnik.Map(self.width, self.height)
            mapfile = "renderer/map_data/styles/bs_" + layer + ".xml"
            mapnik.load_map(m, mapfile)
            
            # ensure the target map projection is mercator
            m.srs = projec.params()
            
            # transform the centre point into the target coord sys
            centre = mapnik.Coord(self.lon+shift_lon, self.lat+shift_lat)  
            transform = mapnik.ProjTransform(longlat, projec)
            merc_centre = transform.forward(centre)
            
            # 360/(2**zoom) degrees = 256 px
            # so in merc 1px = (20037508.34*2) / (256 * 2**zoom)
            # hence to find the bounds of our rectangle in projected coordinates + and - half the image width worth of projected coord units
            
            dx = ((20037508.34*2*(self.width/2)))/(256*(2 ** (zoom)))
            minx = merc_centre.x - dx
            maxx = merc_centre.x + dx
            
            # grow the height bbox, as we only accurately set the width bbox
            m.aspect_fix_mode = mapnik.aspect_fix_mode.ADJUST_BBOX_HEIGHT

            bounds = mapnik.Box2d(minx, merc_centre.y-10, maxx, merc_centre.y+10) # the y bounds will be fixed by mapnik due to ADJUST_BBOX_HEIGHT
            m.zoom_to_box(bounds)

            # render the map image to a file
            # mapnik.render_to_file(m, output)
            #render the map to an image
            im = mapnik.Image(self.width,self.height)
            mapnik.render(m, im)
            img = im.tostring('png256')
            img = cv2.imdecode(np.fromstring(img, dtype=np.uint8), 1)
            img =np.asarray(img)
            data.append(img)
        data = np.stack(data)
        return data
Beispiel #9
0
 def googleBoundsToBox2d(self, google_bounds):
     parts = google_bounds.split(",")
     strip_str = "() "
     min_lat = float(parts[0].strip(strip_str))
     min_lng = float(parts[1].strip(strip_str))
     max_lat = float(parts[2].strip(strip_str))
     max_lng = float(parts[3].strip(strip_str))
     return mapnik2.Box2d(min_lng, min_lat, max_lng, max_lat)
Beispiel #10
0
def test_render_grid():
    places_ds = mapnik2.PointDatasource()
    places_ds.add_point(143.10, -38.60, 'Name', 'South East')
    places_ds.add_point(142.48, -38.60, 'Name', 'South West')
    places_ds.add_point(142.48, -38.38, 'Name', 'North West')
    places_ds.add_point(143.10, -38.38, 'Name', 'North East')
    s = mapnik2.Style()
    r = mapnik2.Rule()
    #symb = mapnik2.PointSymbolizer()
    symb = mapnik2.MarkersSymbolizer()
    symb.allow_overlap = True
    r.symbols.append(symb)
    label = mapnik2.TextSymbolizer(mapnik2.Expression('[Name]'),
                                   'DejaVu Sans Book', 10,
                                   mapnik2.Color('black'))
    label.allow_overlap = True
    label.displacement = (0, -10)
    #r.symbols.append(label)

    s.rules.append(r)
    lyr = mapnik2.Layer('Places')
    lyr.datasource = places_ds
    lyr.styles.append('places_labels')
    m = mapnik2.Map(256, 256)
    m.append_style('places_labels', s)
    m.layers.append(lyr)
    ul_lonlat = mapnik2.Coord(142.30, -38.20)
    lr_lonlat = mapnik2.Coord(143.40, -38.80)
    m.zoom_to_box(mapnik2.Box2d(ul_lonlat, lr_lonlat))
    grid = mapnik2.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)
Beispiel #11
0
def test_render_points():
    # Test for effectivenes of ticket #402 (borderline points get lost on reprojection)
    raise Todo("See: http://trac.mapnik2.org/ticket/402")

    if not mapnik2.has_pycairo(): return

    # create and populate point datasource (WGS84 lat-lon coordinates)
    places_ds = mapnik2.PointDatasource()
    places_ds.add_point(142.48, -38.38, 'Name',
                        'Westernmost Point')  # westernmost
    places_ds.add_point(143.10, -38.60, 'Name',
                        'Southernmost Point')  # southernmost
    # create layer/rule/style
    s = mapnik2.Style()
    r = mapnik2.Rule()
    symb = mapnik2.PointSymbolizer()
    symb.allow_overlap = True
    r.symbols.append(symb)
    s.rules.append(r)
    lyr = mapnik2.Layer('Places', '+proj=latlon +datum=WGS84')
    lyr.datasource = places_ds
    lyr.styles.append('places_labels')
    # latlon bounding box corners
    ul_lonlat = mapnik2.Coord(142.30, -38.20)
    lr_lonlat = mapnik2.Coord(143.40, -38.80)
    # render for different projections
    projs = {
        'latlon': '+proj=latlon +datum=WGS84',
        'merc': '+proj=merc +datum=WGS84 +k=1.0 +units=m +over +no_defs',
        'google': '+proj=merc +ellps=sphere +R=6378137 +a=6378137 +units=m',
        'utm': '+proj=utm +zone=54 +datum=WGS84'
    }
    from cairo import SVGSurface
    for projdescr in projs.iterkeys():
        m = mapnik2.Map(1000, 500, projs[projdescr])
        m.append_style('places_labels', s)
        m.layers.append(lyr)
        p = mapnik2.Projection(projs[projdescr])
        m.zoom_to_box(p.forward(mapnik2.Box2d(ul_lonlat, lr_lonlat)))
        # Render to SVG so that it can be checked how many points are there with string comparison
        import StringIO
        svg_memory_file = StringIO.StringIO()
        surface = SVGSurface(svg_memory_file, m.width, m.height)
        mapnik2.render(m, surface)
        surface.flush()
        surface.finish()
        svg = svg_memory_file.getvalue()
        svg_memory_file.close()
        num_points_present = len(places_ds.all_features())
        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))
Beispiel #12
0
def test_feature_hit_count():
    # results in different results between shp and ogr!
    #bbox = (-14284551.8434, 2074195.1992, -7474929.8687, 8140237.7628)
    bbox = (1113194.91,4512803.085,2226389.82,6739192.905)
    query = mapnik2.Query(mapnik2.Box2d(*bbox))
    ds1 = mapnik2.Ogr(file='../data/shp/world_merc.shp',layer_by_index=0)
    for fld in ds1.fields():
        query.add_property_name(fld)
    ds2 = mapnik2.Shapefile(file='../data/shp/world_merc.shp')
    count1 = len(ds1.features(query).features)
    count2 = len(ds2.features(query).features)
    eq_(count1,count2,"Feature count differs between OGR driver (%s features) and Shapefile Driver (%s features) when querying the same bbox" % (count1,count2))
Beispiel #13
0
def test_layer_init():
    l = mapnik2.Layer('test')
    eq_(l.name,'test')
    eq_(l.envelope(),mapnik2.Box2d())
    eq_(l.clear_label_cache,False)
    eq_(l.cache_features,False)
    eq_(l.visible(),True)
    eq_(l.abstract,'')
    eq_(l.active,True)
    eq_(l.datasource,None)
    eq_(l.queryable,False)
    eq_(l.srs,'+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs')
    eq_(l.title,'')
    def render_tile(self, tile_uri, x, y, z):

        # Calculate pixel positions of bottom-left & top-right
        p0 = (x * 256, (y + 1) * 256)
        p1 = ((x + 1) * 256, y * 256)

        # Convert to LatLong (EPSG:4326)
        l0 = self.tileproj.fromPixelToLL(p0, z)
        l1 = self.tileproj.fromPixelToLL(p1, z)

        # Convert to map projection (e.g. mercator co-ords EPSG:900913)
        c0 = self.prj.forward(mapnik.Coord(l0[0], l0[1]))
        c1 = self.prj.forward(mapnik.Coord(l1[0], l1[1]))

        # Bounding box for the tile
        if hasattr(mapnik,
                   'mapnik_version') and mapnik.mapnik_version() >= 800:
            bbox = mapnik.Box2d(c0.x, c0.y, c1.x, c1.y)
        else:
            bbox = mapnik.Envelope(c0.x, c0.y, c1.x, c1.y)
        render_size = 256
        self.m.resize(render_size, render_size)
        self.m.zoom_to_box(bbox)
        self.m.buffer_size = 128

        # Render image with default Agg renderer
        im = mapnik.Image(render_size, render_size)
        mapnik.render(self.m, im)
        im.save(tile_uri, 'png256')
        grid_uri = tile_uri.replace('.png', '.grid.json')

        # new mapnik.Grid api, works like mapnik.Image
        # with the exception that you can only render one
        # layer to it with the mapnik.render_layer function

        # create grid as same size as map/image
        grid = mapnik.Grid(render_size, render_size)
        # render a layer to that grid array
        mapnik.render_layer(self.m, grid, layer=0, fields=['POP2005', 'NAME'])
        # then encode the grid array as utf, resample to 1/4 the size, and dump features
        grid_utf = grid.encode('utf', resolution=4, add_features=True)

        # below is the old grid api - will be removed soon, don't use
        #grid_utf = mapnik.render_grid(self.m,0,key='__id__',resolution=4,fields=['POP2005','NAME'])
        # client code uses jsonp, so fake by wrapping in grid() callback
        open(grid_uri, 'wb').write('grid(' + json.dumps(grid_utf) + ')')
Beispiel #15
0
    def rpc_renderCoordOld(self, lat, lon, zoom):
        """
        Renders a map for the given coordinates.
        """
        Map = None

        LandmassShapefile = 'cape/Interface/ne_110m_admin_0_countries.shp'

        im = mapnik.Image(self.mapsize[0], self.mapsize[1])
        m = mapnik.Map(self.mapsize[0], self.mapsize[1])

        m.background = mapnik.Color(self.backgroundColor)
        s = mapnik.Style()
        r = mapnik.Rule()
        polygon_symbolizer = mapnik.PolygonSymbolizer(
            mapnik.Color(self.foregroundColor))
        r.symbols.append(polygon_symbolizer)
        line_symbolizer = mapnik.LineSymbolizer(
            mapnik.Color('rgb(50%,50%,50%)'), 0.1)
        r.symbols.append(line_symbolizer)
        s.rules.append(r)
        m.append_style('My Style', s)

        ds = mapnik.Shapefile(file=LandmassShapefile)
        layer = mapnik.Layer('world')
        layer.datasource = ds
        layer.styles.append('My Style')
        m.layers.append(layer)

        center = mapnik.Coord(lat, lon)
        transform = mapnik.ProjTransform(self.longlat, self.merc)
        merc_center = transform.forward(center)

        dx = (20037508.34 * 2 * (self.mapsize[0] / 2)) / (256 * (2**(zoom)))
        minx = merc_center.x - dx
        maxx = merc_center.x + dx

        m.aspect_fix_mode = mapnik.aspect_fix_mode.ADJUST_BBOX_HEIGHT

        merc_bbox = mapnik.Box2d(minx, merc_center.y - 1, maxx,
                                 merc_center.y + 1)
        m.zoom_to_box(merc_bbox)
        mapnik.render(m, im)
        Map = im.tostring('png')

        return (True, Map)
Beispiel #16
0
def test_render_points():

    if not mapnik2.has_cairo(): return

    # create and populate point datasource (WGS84 lat-lon coordinates)
    places_ds = mapnik2.PointDatasource()
    places_ds.add_point(142.48, -38.38, 'Name',
                        'Westernmost Point')  # westernmost
    places_ds.add_point(143.10, -38.60, 'Name',
                        'Southernmost Point')  # southernmost
    # create layer/rule/style
    s = mapnik2.Style()
    r = mapnik2.Rule()
    symb = mapnik2.PointSymbolizer()
    symb.allow_overlap = True
    r.symbols.append(symb)
    s.rules.append(r)
    lyr = mapnik2.Layer('Places', '+proj=latlon +datum=WGS84')
    lyr.datasource = places_ds
    lyr.styles.append('places_labels')
    # latlon bounding box corners
    ul_lonlat = mapnik2.Coord(142.30, -38.20)
    lr_lonlat = mapnik2.Coord(143.40, -38.80)
    # render for different projections
    projs = {
        'latlon': '+proj=latlon +datum=WGS84',
        'merc': '+proj=merc +datum=WGS84 +k=1.0 +units=m +over +no_defs',
        'google': '+proj=merc +ellps=sphere +R=6378137 +a=6378137 +units=m',
        'utm': '+proj=utm +zone=54 +datum=WGS84'
    }
    for projdescr in projs.iterkeys():
        m = mapnik2.Map(1000, 500, projs[projdescr])
        m.append_style('places_labels', s)
        m.layers.append(lyr)
        p = mapnik2.Projection(projs[projdescr])
        m.zoom_to_box(p.forward(mapnik2.Box2d(ul_lonlat, lr_lonlat)))
        # Render to SVG so that it can be checked how many points are there with string comparison
        svg_file = '/tmp/%s.svg'
        mapnik2.render_to_file(m, svg_file)
        num_points_present = len(places_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))
Beispiel #17
0
    def render_location_with_zoom(self, zoom):
        # target projection
        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')

        # WGS lat/long source projection of centrel 
        longlat = mapnik.Projection('+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs')
        
        # make a new Map object for the given mapfile
        m = mapnik.Map(self.width, self.height)
        mapnik.load_map(m, self.mapfile)
        
        # ensure the target map projection is mercator
        m.srs = merc.params()
        
        # transform the centre point into the target coord sys
        centre = mapnik.Coord(self.lon, self.lat)  
        transform = mapnik.ProjTransform(longlat, merc)
        merc_centre = transform.forward(centre)
        
        # 360/(2**zoom) degrees = 256 px
        # so in merc 1px = (20037508.34*2) / (256 * 2**zoom)
        # hence to find the bounds of our rectangle in projected coordinates + and - half the image width worth of projected coord units
        dx = ((20037508.34*2*(self.width/2)))/(256*(2 ** (zoom)))
        minx = merc_centre.x - dx
        maxx = merc_centre.x + dx
        
        # grow the height bbox, as we only accurately set the width bbox
        m.aspect_fix_mode = mapnik.aspect_fix_mode.ADJUST_BBOX_HEIGHT

        bounds = mapnik.Box2d(minx, merc_centre.y-10, maxx, merc_centre.y+10) # the y bounds will be fixed by mapnik due to ADJUST_BBOX_HEIGHT
        m.zoom_to_box(bounds)

        # render the map image to a file
        # mapnik.render_to_file(m, output)


        #render the map to an image
        im = mapnik.Image(self.width,self.height)
        mapnik.render(m, im)
        img = im.tostring('png256')
        img = cv2.imdecode(np.fromstring(img, dtype=np.uint8), 1)
        img =np.asarray(img)
        window_name = "Location"
        cv2.imshow(window_name, img)
        cv2.waitKey(1)
Beispiel #18
0
    def rendertiles(self, cpoint, data, item, label, lat, layer, lon,
                    num_items, projec, zoom):
        # target projection
        #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')
        merc = projec
        # WGS lat/long source projection of centre
        longlat = mapnik.Projection(
            '+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs')

        # make a new Map object for the given mapfile
        m = mapnik.Map(self.width, self.height)
        mapfile = "/map_data/styles/bs_" + layer + ".xml"
        mapnik.load_map(m, mapfile)

        # ensure the target map projection is mercator
        m.srs = merc.params()

        # transform the centre point into the target coord sys
        centre = mapnik.Coord(cpoint[0], cpoint[1])
        transform = mapnik.ProjTransform(longlat, merc)
        merc_centre = transform.forward(centre)

        # 360/(2**zoom) degrees = 256 px
        # so in merc 1px = (20037508.34*2) / (256 * 2**zoom)
        # hence to find the bounds of our rectangle in projected coordinates + and - half the image width worth of projected coord units

        dx = ((20037508.34 * 2 * (self.width / 2))) / (256 * (2**(zoom)))
        minx = merc_centre.x - dx
        maxx = merc_centre.x + dx

        # grow the height bbox, as we only accurately set the width bbox
        m.aspect_fix_mode = mapnik.aspect_fix_mode.ADJUST_BBOX_HEIGHT

        bounds = mapnik.Box2d(
            minx, merc_centre.y - 10, maxx, merc_centre.y + 10
        )  # the y bounds will be fixed by mapnik due to ADJUST_BBOX_HEIGHT
        m.zoom_to_box(bounds)

        # render the map image to a file
        # mapnik.render_to_file(m, output)
        #render the map to an image
        im = mapnik.Image(self.width, self.height)
        mapnik.render(m, im)
        img = im.tostring('png256')
        data[(item, layer)] = img
Beispiel #19
0
def complexRun(image, stylesheet, extent, size):
    mapfile = stylesheet
    map_uri = image

    imgx = size[0]
    imgy = size[1]

    m = mapnik.Map(imgx, imgy)
    mapnik.load_map(m, mapfile)

    if hasattr(mapnik, 'mapnik_version') and mapnik.mapnik_version() >= 800:
        bbox = mapnik.Box2d(extent[0], extent[2], extent[1], extent[3])
    else:
        bbox = mapnik.Envelope(extent[0], extent[2], extent[1], extent[3])
    m.zoom_to_box(bbox)
    im = mapnik.Image(imgx, imgy)
    mapnik.render(m, im)
    view = im.view(0, 0, imgx, imgy)  # x,y,width,height
    view.save(map_uri, 'png')
Beispiel #20
0
    def render_tile(self, tile_uri, x, y, z):
        # Calculate pixel positions of bottom-left & top-right
        p0 = (x * TILES_SIZE, (y + 1) * TILES_SIZE)
        p1 = ((x + 1) * TILES_SIZE, y * TILES_SIZE)

        # Convert to LatLong (EPSG:4326)
        l0 = self.tileproj.fromPixelToLL(p0, z)
        l1 = self.tileproj.fromPixelToLL(p1, z)

        # Convert to map projection (e.g. mercator co-ords EPSG:900913)
        c0 = self.prj.forward(mapnik.Coord(l0[0], l0[1]))
        c1 = self.prj.forward(mapnik.Coord(l1[0], l1[1]))

        # Bounding box for the tile
        if hasattr(mapnik,
                   'mapnik_version') and mapnik.mapnik_version() >= 800:
            bbox = mapnik.Box2d(c0.x, c0.y, c1.x, c1.y)
        else:
            bbox = mapnik.Envelope(c0.x, c0.y, c1.x, c1.y)
        render_size = TILES_SIZE
        self.m.resize(render_size, render_size)
        self.m.zoom_to_box(bbox)
        self.m.buffer_size = 128

        if FORMAT == 'grid':
            grid = mapnik.Grid(render_size, render_size)
            #            mapnik.render_layer(self.m, grid, layer=64, fields=['name'])
            for n, l in enumerate(self.m.layers):
                if l.name != 'admin-012345678':
                    if 'name' in l.datasource.fields():
                        mapnik.render_layer(self.m,
                                            grid,
                                            layer=n,
                                            fields=['name'])
            utfgrid = grid.encode('utf', resolution=4)
            f = open(tile_uri + '.' + FILE_EXTENSION, 'w')
            f.write(json.dumps(utfgrid))
            f.close()
        else:
            # Render image with default Agg renderer
            im = mapnik.Image(render_size, render_size)
            mapnik.render(self.m, im)
            im.save(tile_uri + '.' + FILE_EXTENSION, FORMAT)
Beispiel #21
0
    def rpc_renderCoord(self, lat, lon, zoom):
        im = mapnik.Image(self.mapsize[0], self.mapsize[1])

        center = mapnik.Coord(lat, lon)
        transform = mapnik.ProjTransform(self.longlat, self.merc)
        merc_center = transform.forward(center)

        dx = (20037508.34 * 2 * (self.mapsize[0] / 2)) / (256 * (2**(zoom)))
        minx = merc_center.x - dx
        maxx = merc_center.x + dx

        self.rendermap.aspect_fix_mode = mapnik.aspect_fix_mode.ADJUST_BBOX_HEIGHT

        merc_bbox = mapnik.Box2d(minx, merc_center.y - 1, maxx,
                                 merc_center.y + 1)
        self.rendermap.zoom_to_box(merc_bbox)
        mapnik.render(self.rendermap, im)
        Map = im.tostring('png')

        return (True, Map)
Beispiel #22
0
def test_render_grid2():
    """ test old against new"""
    width,height = 256,256
    m = create_grid_map(width,height)
    ul_lonlat = mapnik2.Coord(142.30,-38.20)
    lr_lonlat = mapnik2.Coord(143.40,-38.80)
    m.zoom_to_box(mapnik2.Box2d(ul_lonlat,lr_lonlat))

    # new method
    grid = mapnik2.Grid(m.width,m.height,key='Name')
    mapnik2.render_layer(m,grid,layer=0,fields=['Name'])
    utf1 = grid.encode('utf',resolution=4)
    eq_(utf1,grid_correct_new)

    # old method - to be removed
    utf2 = mapnik2.render_grid(m,0,key='Name',resolution=4,fields=['Name'])
    eq_(utf2,grid_correct)

    # for complex polygons these will not be true
    eq_(len(utf2['grid']),len(utf1['grid']))
    eq_(len(utf2['keys']),len(utf1['keys']))
    eq_(len(utf2['data']),len(utf1['data']))
    
    # check a full view is the same as a full image
    grid_view = grid.view(0,0,width,height)
    # for kicks check at full res too
    utf3 = grid.encode('utf',resolution=1)
    utf4 = grid_view.encode('utf',resolution=1)
    eq_(utf3['grid'],utf4['grid'])
    eq_(utf3['keys'],utf4['keys'])
    eq_(utf3['data'],utf4['data'])
    
    eq_(resolve(utf4,0,0),None)
    
    # resolve some center points in the
    # resampled view
    utf5 = grid_view.encode('utf',resolution=4)
    eq_(resolve(utf5,25,10),{"Name": "North West"})
    eq_(resolve(utf5,25,46),{"Name": "North East"})
    eq_(resolve(utf5,38,10),{"Name": "South West"})
    eq_(resolve(utf5,38,46),{"Name": "South East"})
Beispiel #23
0
    def renderTile(self, width, height, srs, coord):
        """
        """
        if self.mapnik is None:
            self.mapnik = mapnik.Map(0, 0)
            mapnik.load_map(self.mapnik, str(self.mapfile))

        # buffer as fraction of tile size
        buffer = float(self.buffer) / 256

        nw = self.layer.projection.coordinateLocation(
            coord.left(buffer).up(buffer))
        se = self.layer.projection.coordinateLocation(
            coord.right(1 + buffer).down(1 + buffer))
        ul = self.mercator.locationProj(nw)
        lr = self.mercator.locationProj(se)

        self.mapnik.width = width + 2 * self.buffer
        self.mapnik.height = height + 2 * self.buffer
        self.mapnik.zoom_to_box(mapnik.Box2d(ul.x, ul.y, lr.x, lr.y))

        # create grid as same size as map/image
        grid = mapnik.Grid(width + 2 * self.buffer, height + 2 * self.buffer)
        # render a layer to that grid array
        mapnik.render_layer(self.mapnik,
                            grid,
                            layer=self.layer_index,
                            fields=self.fields)
        # extract a gridview excluding the buffer
        grid_view = grid.view(self.buffer, self.buffer, width, height)
        # then encode the grid array as utf, resample to 1/scale the size, and dump features
        grid_utf = grid_view.encode('utf',
                                    resolution=self.scale,
                                    add_features=True)

        if self.wrapper is None:
            return SaveableResponse(json.dumps(grid_utf))
        else:
            return SaveableResponse(self.wrapper + '(' + json.dumps(grid_utf) +
                                    ')')
Beispiel #24
0
    def render_tile(self, tile_uri, x, y, z):
        # Calculate pixel positions of bottom-left & top-right
        #        start=time.time()
        #        p0 = (x * TILESIZE, (y + 1) * TILESIZE)
        #        p1 = ((x + 1) * TILESIZE, y * TILESIZE)
        #
        #        # Convert to LatLong (EPSG:4326)
        #        l0 = self.tileproj.fromPixelToLL(p0, z);
        #        l1 = self.tileproj.fromPixelToLL(p1, z);
        #
        #        # Convert to map projection (e.g. mercator co-ords EPSG:900913)
        #        c0 = self.prj.forward(mapnik2.Coord(l0[0],l0[1]))
        #        c1 = self.prj.forward(mapnik2.Coord(l1[0],l1[1]))

        l0y, l0x = num2deg(x, y + 1, z)
        l1y, l1x = num2deg(x + 1, y, z)

        # Convert to map projection (e.g. mercator co-ords EPSG:900913)
        c0 = self.prj.forward(mapnik2.Coord(l0x, l0y))
        c1 = self.prj.forward(mapnik2.Coord(l1x, l1y))

        # Bounding box for the tile
        if hasattr(mapnik2,
                   'mapnik_version') and mapnik2.mapnik_version() >= 800:
            bbox = mapnik2.Box2d(c0.x, c0.y, c1.x, c1.y)
        else:
            bbox = mapnik2.Envelope(c0.x, c0.y, c1.x, c1.y)
        render_size = TILESIZE
        self.m.resize(render_size, render_size)
        self.m.zoom_to_box(bbox)
        self.m.buffer_size = 128

        # Render image with default Agg renderer
        im = mapnik2.Image(render_size, render_size)
        #        print("%f"%(time.time()-start))
        #        start=time.time()
        mapnik2.render(self.m, im)
        #        print("%f"%(time.time()-start))
        #        start=time.time()
        im.save(tile_uri, 'png256')
def create_map_and_append_symbolyzer(sym):
    srs = '+init=epsg:32630'
    lyr = mapnik2.Layer('arrows')
    lyr.datasource = mapnik2.Shapefile(file='../data/shp/arrows.shp', )
    lyr.srs = srs
    _map = mapnik2.Map(256, 256, srs)
    style = mapnik2.Style()
    rule = mapnik2.Rule()
    rule.symbols.append(sym)

    # put a test symbolizer to see what is the azimuth being read
    ts = mapnik2.TextSymbolizer(mapnik2.Expression('[azimuth]'),
                                "DejaVu Sans Book", 10, mapnik2.Color("black"))
    ts.allow_overlap = True
    rule.symbols.append(ts)

    style.rules.append(rule)
    _map.append_style('foo', style)
    lyr.styles.append('foo')
    _map.layers.append(lyr)
    _map.zoom_to_box(mapnik2.Box2d(0, 0, 8, 8))
    return _map
Beispiel #26
0
    def generate_map_tile(self, m, filename, z, x, y):
        # Code taken from OSM generate_tiles.py
        proj = GoogleProjection()
        mprj = mapnik.Projection(m.srs)

        p0 = (x * 256, (y + 1) * 256)
        p1 = ((x + 1) * 256, y * 256)
        l0 = proj.fromPixelToLL(p0, z);
        l1 = proj.fromPixelToLL(p1, z);
        c0 = mprj.forward(mapnik.Coord(l0[0], l0[1]))
        c1 = mprj.forward(mapnik.Coord(l1[0], l1[1]))

        if hasattr(mapnik,'mapnik_version') and mapnik.mapnik_version() >= 800:
            bbox = mapnik.Box2d(c0.x, c0.y, c1.x, c1.y)
        else:
            bbox = mapnik.Envelope(c0.x, c0.y, c1.x, c1.y)

        m.resize(256, 256)
        m.zoom_to_box(bbox)

        im = mapnik.Image(256, 256)
        mapnik.render(m, im)
        im.save(str(filename), "png256")
Beispiel #27
0
def rendertiles( bounds, item, label, lat, layers, lon, projec, writer):
    z = 1
    imgx = 128 * z
    imgy = 128 * z
    
    for layer in layers:
        index = layers.index(layer)
        mapfile = "/map_data/styles/bs_" + layer + ".xml"
     
        m = mapnik.Map(imgx,imgy)
        mapnik.load_map(m,mapfile)
        # ensure the target map projection is mercator
        m.srs = projec.params()
        
        if hasattr(mapnik,'Box2d'):
            bbox = mapnik.Box2d(*bounds)
        else:
            bbox = mapnik.Envelope(*bounds)

        transform = mapnik.ProjTransform(longlat,projec)
        merc_bbox = transform.forward(bbox)
        
        m.zoom_to_box(merc_bbox)
        
        # render the map to an image
        im = mapnik.Image(imgx,imgy)
        mapnik.render(m, im)
        
        img = im.tostring('png256')
        
        if index == 0:
            data=[img]
            #data = np.expand_dims(data, 0) 
        else:            
            data.append(img)    
                    
    save_data(data, layers, item, label, lat, lon, writer)
Beispiel #28
0
def test_envelope_init():
    e = mapnik2.Box2d(100, 100, 200, 200)

    assert_true(e.contains(100, 100))
    assert_true(e.contains(100, 200))
    assert_true(e.contains(200, 200))
    assert_true(e.contains(200, 100))

    assert_true(e.contains(e.center()))
    
    assert_false(e.contains(99.9, 99.9))
    assert_false(e.contains(99.9, 200.1))
    assert_false(e.contains(200.1, 200.1))
    assert_false(e.contains(200.1, 99.9))

    eq_(e.width(), 100)
    eq_(e.height(), 100)

    eq_(e.minx, 100)
    eq_(e.miny, 100)

    eq_(e.maxx, 200)
    eq_(e.maxy, 200)
    
    eq_(e[0],100)
    eq_(e[1],100)
    eq_(e[2],200)
    eq_(e[3],200)
    eq_(e[0],e[-4])
    eq_(e[1],e[-3])
    eq_(e[2],e[-2])
    eq_(e[3],e[-1])
    
    c = e.center()

    eq_(c.x, 150)
    eq_(c.y, 150)
Beispiel #29
0
 def render_tile(self, zoom, x, y):
     t0 = time.time()
     tl = "(zoom=%s x=%s y=%s)" % (zoom, x, y)
     self.log("Rendering tile %s" % tl)
     # Convert tile index to LatLong (EPSG:4326)
     l0 = xy_to_ll(zoom, (x, y + 1))
     l1 = xy_to_ll(zoom, (x + 1, y))
     # Convert to map projection (e.g. mercator co-ords EPSG:900913)
     # and get tile's bounding box
     c0 = self.prj.forward(mapnik2.Coord(l0[0], l0[1]))
     c1 = self.prj.forward(mapnik2.Coord(l1[0], l1[1]))
     bbox = mapnik2.Box2d(c0.x, c0.y, c1.x, c1.y)
     # Render
     self.m.resize(TS, TS)
     self.m.zoom_to_box(bbox)
     self.m.buffer_size = 128
     im = mapnik2.Image(TS, TS)
     mapnik2.render(self.m, im)
     data = im.tostring("png256")
     # Save to database
     tc = TileCache.objects.filter(map=self.map.id, zoom=zoom, x=x,
                                   y=y).first()
     if tc:
         tc.ready = True
         tc.last_updated = datetime.datetime.now()
         tc.data = data
         tc.save()
     else:
         TileCache(map=self.map.id,
                   zoom=zoom,
                   x=x,
                   y=y,
                   ready=True,
                   last_updated=datetime.datetime.now(),
                   data=data).save()
     self.log("Tile %s completed in %dms" % (tl, (time.time() - t0) * 1000))
Beispiel #30
0
def test_envelope_pickle():
    e1 = mapnik2.Box2d(-180, -90, 180, 90)
    e2 = mapnik2.Box2d(-120, 40, -110, 48)
    e1.clip(e2)
    eq_(e1, e2)

    # madagascar in merc
    e1 = mapnik2.Box2d(4772116.5490, -2744395.0631, 5765186.4203,
                       -1609458.0673)
    e2 = mapnik2.Box2d(5124338.3753, -2240522.1727, 5207501.8621,
                       -2130452.8520)
    e1.clip(e2)
    eq_(e1, e2)

    # nz in lon/lat
    e1 = mapnik2.Box2d(163.8062, -47.1897, 179.3628, -33.9069)
    e2 = mapnik2.Box2d(173.7378, -39.6395, 174.4849, -38.9252)
    e1.clip(e2)
    eq_(e1, e2)