Example #1
0
    def create_tile(self, tile_x, tile_y, zoom, style):
        m = mapnik2.Map(256, 256)
        m.append_style('data_style', style)
        lyr = mapnik2.Layer('Geometry from PostGIS')
    
        bounds = self.global_mercator.TileBounds(tile_x, tile_y, zoom)
    
        params = dict(
            host=str(self.db["host"]),
            user=str(self.db["user"]),
            password=str(self.db["password"]),
            dbname=str(self.db["database"]),
            table=str(self.geography["table"]),
            estimate_extent=False,
            extent=','.join(map(str, bounds)) #'-20037508,-19929239,20037508,19929239'
        ) 
    
        lyr.datasource = mapnik2.PostGIS(**params)

        lyr.styles.append('data_style')
        m.layers.append(lyr)
        m.zoom_to_box(lyr.envelope())
    
        goog_x, goog_y = self.global_mercator.GoogleTile(tile_x, tile_y, zoom)
    
        file_name = '../tiles/%d_%d_%d.png' % (zoom, goog_x, goog_y)
        mapnik2.render_to_file(m, file_name, 'png')
Example #2
0
 def get(self):
     mapfile = os.path.join(DATA_PATH, 'hazard', 'flood.shp')
     #mapfile = os.path.join(DATA_PATH, 'impact', 'impact.json')
     filename = os.path.join(DATA_PATH, 'pdf', 'report_map.pdf')
     filename2 = os.path.join(DATA_PATH, 'pdf', 'report_map.png')
     map = mapnik2.Map(600, 400)
     
     map.background = mapnik2.Color('steelblue')
     s = mapnik2.Style()
     r = mapnik2.Rule()
     polygon_symbolizer = mapnik2.PolygonSymbolizer(mapnik2.Color('#f2eff9'))
     r.symbols.append(polygon_symbolizer)
     line_symbolizer = mapnik2.LineSymbolizer(mapnik2.Color('rgb(50%,50%,50%)'),0.1)
     r.symbols.append(line_symbolizer)
     s.rules.append(r)
     map.append_style('My Style',s)
     ds = mapnik2.Shapefile(file=mapfile)
     layer = mapnik2.Layer('world')
     layer.datasource = ds
     layer.styles.append('My Style')
     map.layers.append(layer)
     map.zoom_all()
     mapnik2.render_to_file(map, filename2, 'png')
     
     #bbox = mapnik.Envelope(-180.0,-90.0,180.0,90.0)
     #map.zoom_to_box(bbox)
     surface = cairo.PDFSurface(filename, map.width, map.height)
     mapnik2.render(map, surface)
     surface.finish()
     
     with open(filename) as data:
         pdf = data.read()
         data.close()
         self.set_header("Content-Type", "application/pdf")
         self.write(pdf)
def create_testmap_db_point():
    map_out = "map_pi.png"
    m = mapnik2.Map(1024, 768)

    style = mapnik2.Style()
    rule = mapnik2.Rule()
    rs = mapnik2.RasterSymbolizer()
    rule.symbols.append(rs)
    style.rules.append(rule)
    m.append_style('raster',style)
    lyr = mapnik2.Layer('raster')
    lyr.datasource = mapnik2.Gdal(base='..', file="world_one_mapCLIPPED.tif")
    lyr.styles.append('raster') 
    m.layers.append(lyr)


    symbolizer = mapnik2.PointSymbolizer(mapnik2.PathExpression("draw_circle.png"))
    symbolizer.allow_overlap = True
    symbolizer.fill_opacity = 0.5
    symbolizer.gamma = 0.0
    rule.symbols.append(symbolizer)
    style2 = mapnik2.Style()
    style2.rules.append(rule)
    layer2 = mapnik2.Layer("mapLayer")
    layer2.datasource = mapnik2.SQLite(file="../test-2.3.sqlite", table='(SELECT * FROM Towns WHERE Peoples < 500) as data', key_field='PK_UID', geometry_field='GEOMETRY', wkb_format='spatialite', extent="319224,3934670,1308590,5214370")
    print layer2.datasource.describe()
    layer2.styles.append("mapStyle")
    m.background = mapnik2.Color("red")
    m.append_style("mapStyle", style2)
    m.layers.append(layer2)

    m.zoom_all()   
    mapnik2.render_to_file(m, map_out, 'png')
Example #4
0
    def cache_map(self, minlat, minlng, maxlat, maxlng):
        print "Downloading map data."
        conn = urllib2.urlopen('http://overpass-api.de/api/xapi?map?bbox=%f,%f,%f,%f' %
                              (minlng, minlat, maxlng, maxlat))
        fn = self.mapdir + 'dat.osm'
        with open(fn, 'w') as f:
            s = conn.read(65536)
            while s:
                f.write(s)
                s = conn.read(65536)
        conn.close()

        print "Saving bounds."
        bounds_dictionary = { 'minlat': minlat, 'minlng': minlng, 'maxlat': maxlat, 'maxlng': maxlng }
        fn = self.mapdir + 'bounds.pkl'
        with open(fn, 'w') as f:
            pickle.dump(bounds_dictionary, f)

        for layer in self.mapn.layers:
            layer.datasource = mapnik2.Osm(file=os.path.join(self.mapdir, 'dat.osm'))

        self.mapn.resize(int(self.mapwidth * (maxlng - minlng) / self.dlat * sin((maxlat + minlat)/2)),
                         int(self.mapheight * (maxlat - minlat) / self.dlat))
        self.mapn.zoom_to_box(self.projection.forward(mapnik2.Envelope(minlng, minlat, maxlng, maxlat)))

        print "Saving base map image."
        filename = self.mapdir + self.map_output
        mapnik2.render_to_file(self.mapn, filename)
        self.largemapimg = Image.open(filename)
def create_testmap_db():
    map_out = "map_from_db.png"
    m = mapnik2.Map(1024, 768)

    style = mapnik2.Style()
    rule = mapnik2.Rule()
    rs = mapnik2.RasterSymbolizer()
    rule.symbols.append(rs)
    style.rules.append(rule)
    m.append_style('raster',style)
    lyr = mapnik2.Layer('raster')
    lyr.datasource = mapnik2.Gdal(base='..', file="world_one_mapCLIPPED.tif")
    lyr.styles.append('raster') 
    m.layers.append(lyr)


    symbolizer = mapnik2.PolygonSymbolizer(mapnik2.Color(255, 0, 0))
    symbolizer.fill_opacity = 0.5
    symbolizer.gamma = 0.0
    rule.symbols.append(symbolizer)
    style2 = mapnik2.Style()
    style2.rules.append(rule)
    layer2 = mapnik2.Layer("mapLayer")
    layer2.datasource = mapnik2.SQLite(file="../border.sqlite", table='border', key_field='OGC_FID', geometry_field='GEOMETRY', wkb_format='spatialite', extent='-64.5721,31.0319,-4.50204,61.8924')
    layer2.styles.append("mapStyle")
    m.background = mapnik2.Color("steelblue")
    m.append_style("mapStyle", style2)
    m.layers.append(layer2)

    m.zoom_all()   
    mapnik2.render_to_file(m, map_out, 'png')
Example #6
0
def test_gen_map():
    mapxmlfile = '../data/good_maps/raster_colorizer.xml'
    mapxmloutputfile = 'raster_colorizer_test_save.xml'
    outputfile = 'raster_colorizer_test.png'

    m = mapnik2.Map(800, 600)
    mapnik2.load_map(m, mapxmlfile)
    mapnik2.save_map(m, mapxmloutputfile)
    m.zoom_all()
    mapnik2.render_to_file(m, outputfile)
Example #7
0
def test_gen_map():
    mapxmlfile = '../data/good_maps/raster_colorizer.xml'
    mapxmloutputfile = 'raster_colorizer_test_save.xml'
    outputfile = 'raster_colorizer_test.png'

    m = mapnik2.Map(800, 600)
    mapnik2.load_map(m, mapxmlfile)
    mapnik2.save_map(m, mapxmloutputfile)
    m.zoom_all()
    mapnik2.render_to_file(m, outputfile)
Example #8
0
def run(image, stylesheet):
	#stylesheet = 'world_style.xml'
	#image = 'world_style.png'
	imgx = 600
	imgy = 300
	m = mapnik.Map(imgx, imgy)
	mapnik.load_map(m, stylesheet)
	m.zoom_all() 
	mapnik.render_to_file(m, image)
	#print "rendered image to '%s'" % image
	return image
Example #9
0
def run(image, stylesheet):
    #stylesheet = 'world_style.xml'
    #image = 'world_style.png'
    imgx = 600
    imgy = 300
    m = mapnik.Map(imgx, imgy)
    mapnik.load_map(m, stylesheet)
    m.zoom_all()
    mapnik.render_to_file(m, image)
    #print "rendered image to '%s'" % image
    return image
Example #10
0
 def async_get(self, mapnik_map):
     envelope = self.application._merc.xyz_to_envelope(self.x,
             self.y,
             self.z,
             self.tms_style)
     mapnik_map.zoom_to_box(envelope)
     mapnik_map.buffer_size = options.buffer_size
     try:
         if options.tile_cache:
             mapnik_map.set_metawriter_property('tile_dir', 
                 self.application._tile_cache.local_dir(self.mapfile, ''))
             mapnik_map.set_metawriter_property('z', str(self.z))
             mapnik_map.set_metawriter_property('x', str(self.x))
             mapnik_map.set_metawriter_property('y', str(self.y))
             url = "%d/%d/%d.%s" % (self.z, self.x, self.y, self.filetype)
             self.application._tile_cache.prepare_dir(self.mapfile, url)
             mapnik.render_to_file(mapnik_map, 
                 self.application._tile_cache.local_url(self.mapfile, url))
             if self.application._tile_cache.contains(self.mapfile, 
                 "%d/%d/%d.%s" % (self.z, self.x, self.y, self.filetype)):
                 self.set_header('Content-Type', 'image/png')
                 self.write(self.application._tile_cache.get(self.mapfile, 
                     "%d/%d/%d.%s" % (self.z, self.x, self.y, self.filetype)))
                 if self.application._tile_cache.contains(self.mapfile, 
                     "%d/%d/%d.%s" % (self.z, self.x, self.y, 'json')):
                     code_string = self.fString(self.mapfile, self.z, self.x, self.y)
                     jsonp_str = "%s(%s)" % (code_string, json_encode({
                       'features': json_decode(str(self.application._tile_cache.get(self.mapfile, 
                         "%d/%d/%d.%s" % (self.z, self.x, self.y, 'json')))),
                       'code_string': code_string}))
                     self.application._tile_cache.set(self.mapfile,
                       "%d/%d/%d.%s" % (self.z, self.x, self.y, 'json'), jsonp_str)
                 self.finish()
             return
         else:
             im = mapnik.Image(options.tilesize, options.tilesize)
             mapnik.render(mapnik_map, im)
             self.set_header('Content-Type', 'image/png')
             im_data = im.tostring('png')
             self.write(im_data)
             self.finish()
         return
     except RuntimeError:
         logging.error('Map for %s failed to render, cache reset', self.mapfile)
         self.application._map_cache.remove(self.mapfile)
         # Retry exactly once to re-render this tile.
         if not hasattr(self, 'retry'):
             self.retry = True
             self.get(self.mapfile, 'tms', self.z, self.x, self.y, self.filetype)
def test_gen_map():
    mapxmlfile = '../data/good_maps/raster_colorizer.xml'
    mapxmloutputfile = 'raster_colorizer_test_save.xml'
    outputfile = 'raster_colorizer_test.png'

    m = mapnik2.Map(800, 600)
    try:
        mapnik2.load_map(m, mapxmlfile)
        mapnik2.save_map(m, mapxmloutputfile)
        m.zoom_all()
        mapnik2.render_to_file(m, outputfile)
    except RuntimeError,e:
        # only test datasources that we have installed
        if not 'Could not create datasource' in str(e):
            raise RuntimeError(str(e))
Example #12
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),
        )
Example #13
0
def render_to_file(mapnik_map,output,format):
    
    # get the full path for a users directory
    if '~' in output:
        output = os.path.expanduser(output)
        
    # mapnik won't create directories so
    # we have to make sure they exist first...
    dirname = os.path.dirname(output)
    if not os.path.exists(dirname):
        os.makedirs(dirname)
    # render out to the desired format
    if format in ('png','png256','jpeg') or (hasattr(mapnik,'mapnik_version') and mapnik.mapnik_version() >= 700):
        try:
            mapnik.render_to_file(mapnik_map,output,format)
        except Exception, e:
            return (False,e)            
Example #14
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))
Example #15
0
    def async_get(self, mapnik_map):
        envelope = self.application._merc.xyz_to_envelope(self.x, self.y, self.z)
        mapnik_map.zoom_to_box(envelope)
        mapnik_map.buffer_size = options.buffer_size
        try:
            # TODO: this makes dangerous assumptions about the content of the file string
            mapnik_map.set_metawriter_property('tile_dir', 
                self.application._tile_cache.local_dir(self.mapfile, ''))

            mapnik_map.set_metawriter_property('z', str(self.z))
            mapnik_map.set_metawriter_property('x', str(self.x))
            mapnik_map.set_metawriter_property('y', str(self.y))

            url = "%d/%d/%d.%s" % (self.z, self.x, self.y, 'png')
            self.application._tile_cache.prepare_dir(self.mapfile, url)
            code_string = self.fString(self.mapfile_64, self.z, self.x, self.y)

            mapnik.render_to_file(mapnik_map, 
                self.application._tile_cache.local_url(self.mapfile, url))

            self.set_header('Content-Type', 'text/javascript')
            code_string = self.fString(self.mapfile, self.z, self.x, self.y)
            jsonp_str = "%s(%s)" % (code_string, json_encode({
              'features': json_decode(str(self.application._tile_cache.get(self.mapfile, 
                "%d/%d/%d.%s" % (self.z, self.x, self.y, 'json')))),
              'code_string': code_string}))
            self.application._tile_cache.set(self.mapfile,
              "%d/%d/%d.%s" % (self.z, self.x, self.y, 'json'), jsonp_str)
            self.write(self.application._tile_cache.get(self.mapfile_64, 
                "%d/%d/%d.%s" % (self.z, self.x, self.y, self.filetype)))
            self.finish()
        except RuntimeError:
            logging.error('Map for %s failed to render, cache reset', self.mapfile)
            self.application._map_cache.remove(self.mapfile)
            # Retry exactly once to re-render this tile.
            if not hasattr(self, 'retry'):
                self.retry = True
                self.get(self.mapfile, self.z, self.x, self.y, self.filetype)
Example #16
0
    def get(self):
        mapfile = os.path.join(DATA_PATH, 'hazard', 'flood.shp')
        #mapfile = os.path.join(DATA_PATH, 'impact', 'impact.json')
        filename = os.path.join(DATA_PATH, 'pdf', 'report_map.pdf')
        filename2 = os.path.join(DATA_PATH, 'pdf', 'report_map.png')
        map = mapnik2.Map(600, 400)

        map.background = mapnik2.Color('steelblue')
        s = mapnik2.Style()
        r = mapnik2.Rule()
        polygon_symbolizer = mapnik2.PolygonSymbolizer(
            mapnik2.Color('#f2eff9'))
        r.symbols.append(polygon_symbolizer)
        line_symbolizer = mapnik2.LineSymbolizer(
            mapnik2.Color('rgb(50%,50%,50%)'), 0.1)
        r.symbols.append(line_symbolizer)
        s.rules.append(r)
        map.append_style('My Style', s)
        ds = mapnik2.Shapefile(file=mapfile)
        layer = mapnik2.Layer('world')
        layer.datasource = ds
        layer.styles.append('My Style')
        map.layers.append(layer)
        map.zoom_all()
        mapnik2.render_to_file(map, filename2, 'png')

        #bbox = mapnik.Envelope(-180.0,-90.0,180.0,90.0)
        #map.zoom_to_box(bbox)
        surface = cairo.PDFSurface(filename, map.width, map.height)
        mapnik2.render(map, surface)
        surface.finish()

        with open(filename) as data:
            pdf = data.read()
            data.close()
            self.set_header("Content-Type", "application/pdf")
            self.write(pdf)
Example #17
0
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
#

import mapnik2

mapfile = 'tutorial2.xml'
map_output = '~/geodata/raster/world/hello_world_using_xml_config.png'
map_output = 'hello_world_using_xml_config.png'

# Instantiate a map object with given width, height and spatial reference system
#m = mapnik.Map(600,300,"+proj=latlong +datum=WGS84")
m = mapnik2.Map(600, 300)

mapnik2.load_map(m, mapfile)
bbox = mapnik2.Envelope(mapnik2.Coord(-180.0, -90.0),
                        mapnik2.Coord(180.0, 90.0))
m.zoom_to_box(bbox)

# Write the data to a png image called world.png in the base directory of your user
mapnik2.render_to_file(m, map_output)

# Exit the python interpreter
exit()
Example #18
0
def mapnik_rendering(f_pct, f_vct, f_render):
    import mapnik2 as mapnik

    ref_pct = GR.geo_raster.open(f_pct)
    proj = ref_pct.projection
    tr = ref_pct.geo_transform
    width = ref_pct.width
    height = ref_pct.height
    size_p = tr[1]
    minx = tr[0]
    maxy = tr[3]
    miny = tr[3] - height * size_p
    maxx = tr[0] + width * size_p
    bbox = (minx, miny, maxx, maxy)

    #---- init
    _map = mapnik.Map(width, height)
    _map.background = mapnik.Color('black')
    #'''
    #----==== shape
    style_vct = mapnik.Style()  # style object to hold rules
    rule_vct = mapnik.Rule()  # rule object to hold symbolizers
    symbol_vct = mapnik.PolygonSymbolizer(mapnik.Color('#f2eff9'))
    symbol_vct.opacity = 0.8
    rule_vct.symbols.append(
        symbol_vct)  # add the symbolizer to the rule object
    line_symbolizer = mapnik.LineSymbolizer(mapnik.Color('rgb(50%,50%,50%)'),
                                            0.1)
    rule_vct.symbols.append(
        line_symbolizer)  # add the symbolizer to the rule object
    style_vct.rules.append(
        rule_vct)  # now add the rule to the style and we're done
    _map.append_style(
        'vector', style_vct
    )  # Styles are given names only as they are applied to the map
    ds_shp = mapnik.Shapefile(file=f_vct)
    mlyr_shp = mapnik.Layer('lakes')
    mlyr_shp.srs = '+proj=utm +zone=46 +ellps=WGS84 +units=m +no_defs '
    mlyr_shp.datasource = ds_shp
    mlyr_shp.styles.append('vector')
    _map.layers.append(mlyr_shp)
    #'''
    #----==== raster
    style_gdal = mapnik.Style()  # style object to hold rules
    rule_gdal = mapnik.Rule()  # rule object to hold symbolizers
    symbol_gdal = mapnik.RasterSymbolizer()
    #symbol_gdal.mode = 'multiply'
    symbol_gdal.opacity = 0.5
    #symbol_gdal.colorizer = mapnik.RasterColorizer(mapnik.COLORIZER_INHERIT, mapnik.Color(0,255,255))

    c = mapnik.RasterColorizer(mapnik.COLORIZER_LINEAR,
                               mapnik.Color(255, 0, 0))

    c.epsilon = 0.001
    c.add_stop(0)
    c.add_stop(255, mapnik.COLORIZER_LINEAR, mapnik.Color("red"))
    c.get_color(255)
    c.stops[1].color
    #'''
    symbol_gdal.colorizer = c

    rule_gdal.symbols.append(symbol_gdal)
    style_gdal.rules.append(rule_gdal)
    _map.append_style("Raster Style", style_gdal)
    mlyr_gdal = mapnik.Layer('TM_images')
    mlyr_gdal.datasource = mapnik.Gdal(file=f_pct, band=1, bbox=bbox)
    mlyr_gdal.srs = '+proj=utm +zone=46 +ellps=WGS84 +units=m +no_defs '
    mlyr_gdal.styles.append('Raster Style')
    _map.layers.append(mlyr_gdal)

    #====
    style_gdal1 = mapnik.Style()  # style object to hold rules
    rule_gdal1 = mapnik.Rule()  # rule object to hold symbolizers
    symbol_gdal1 = mapnik.RasterSymbolizer()
    #symbol_gdal.mode = 'multiply'
    symbol_gdal1.opacity = 0.5
    #symbol_gdal.colorizer = mapnik.RasterColorizer(mapnik.COLORIZER_INHERIT, mapnik.Color(0,255,255))

    c1 = mapnik.RasterColorizer(mapnik.COLORIZER_LINEAR,
                                mapnik.Color(0, 255, 0))

    c1.epsilon = 0.001
    c1.add_stop(0)
    c1.add_stop(255, mapnik.COLORIZER_LINEAR, mapnik.Color("green"))
    c1.get_color(255)
    c1.stops[1].color
    #'''
    symbol_gdal1.colorizer = c1

    rule_gdal1.symbols.append(symbol_gdal1)
    style_gdal1.rules.append(rule_gdal1)
    _map.append_style("Raster Style2", style_gdal1)
    mlyr_gdal1 = mapnik.Layer('TM_images2')
    mlyr_gdal1.datasource = mapnik.Gdal(file=f_pct, band=2, bbox=bbox)
    mlyr_gdal1.srs = '+proj=utm +zone=46 +ellps=WGS84 +units=m +no_defs '
    mlyr_gdal1.styles.append('Raster Style2')
    _map.layers.append(mlyr_gdal1)

    #====
    #====
    style_gdal_b = mapnik.Style()  # style object to hold rules
    rule_gdal_b = mapnik.Rule()  # rule object to hold symbolizers
    symbol_gdal_b = mapnik.RasterSymbolizer()
    #symbol_gdal.mode = 'multiply'
    symbol_gdal_b.opacity = 0.5
    #symbol_gdal.colorizer = mapnik.RasterColorizer(mapnik.COLORIZER_INHERIT, mapnik.Color(0,255,255))

    c_b = mapnik.RasterColorizer(mapnik.COLORIZER_LINEAR,
                                 mapnik.Color(0, 0, 255))

    c_b.epsilon = 0.001
    c_b.add_stop(0)
    c_b.add_stop(255, mapnik.COLORIZER_LINEAR, mapnik.Color("blue"))
    c_b.get_color(255)
    c_b.stops[1].color
    #'''
    symbol_gdal_b.colorizer = c_b

    rule_gdal_b.symbols.append(symbol_gdal_b)
    style_gdal_b.rules.append(rule_gdal_b)
    _map.append_style("Raster Style3", style_gdal_b)
    mlyr_gdal_b = mapnik.Layer('TM_images3')
    mlyr_gdal_b.datasource = mapnik.Gdal(file=f_pct, band=3, bbox=bbox)
    mlyr_gdal_b.srs = '+proj=utm +zone=46 +ellps=WGS84 +units=m +no_defs '
    mlyr_gdal_b.styles.append('Raster Style3')
    _map.layers.append(mlyr_gdal_b)

    #====

    _map.zoom_all()

    # Write the data to a png image called world.png the current directory
    mapnik.render_to_file(_map, f_render, 'png')
Example #19
0
def mapnik_rendering(f_pct,f_vct,f_render):
	import mapnik2 as mapnik

	ref_pct = GR.geo_raster.open(f_pct)
	proj = ref_pct.projection
	tr = ref_pct.geo_transform
	width = ref_pct.width
	height = ref_pct.height
	size_p = tr[1]
	minx = tr[0]
	maxy = tr[3]
	miny = tr[3] - height * size_p
	maxx = tr[0] + width * size_p
	bbox = (minx, miny, maxx, maxy)

	#---- init
	_map = mapnik.Map(width,height)
	_map.background = mapnik.Color('black')
	#'''
	#----==== shape
	style_vct = mapnik.Style() # style object to hold rules
	rule_vct = mapnik.Rule() # rule object to hold symbolizers
	symbol_vct = mapnik.PolygonSymbolizer(mapnik.Color('#f2eff9'))
	symbol_vct.opacity = 0.8
	rule_vct.symbols.append(symbol_vct) # add the symbolizer to the rule object
	line_symbolizer = mapnik.LineSymbolizer(mapnik.Color('rgb(50%,50%,50%)'),0.1)
	rule_vct.symbols.append(line_symbolizer) # add the symbolizer to the rule object
	style_vct.rules.append(rule_vct) # now add the rule to the style and we're done
	_map.append_style('vector',style_vct) # Styles are given names only as they are applied to the map
	ds_shp = mapnik.Shapefile(file=f_vct)
	mlyr_shp = mapnik.Layer('lakes') 
	mlyr_shp.srs = '+proj=utm +zone=46 +ellps=WGS84 +units=m +no_defs '
	mlyr_shp.datasource = ds_shp
	mlyr_shp.styles.append('vector')
	_map.layers.append(mlyr_shp)
	#'''
	#----==== raster
	style_gdal = mapnik.Style() # style object to hold rules
	rule_gdal = mapnik.Rule() # rule object to hold symbolizers
	symbol_gdal = mapnik.RasterSymbolizer()
	#symbol_gdal.mode = 'multiply'
	symbol_gdal.opacity = 0.5
	#symbol_gdal.colorizer = mapnik.RasterColorizer(mapnik.COLORIZER_INHERIT, mapnik.Color(0,255,255))
	
	c = mapnik.RasterColorizer( mapnik.COLORIZER_LINEAR , mapnik.Color(255,0,0) )
	
	c.epsilon = 0.001
	c.add_stop(0)
	c.add_stop(255, mapnik.COLORIZER_LINEAR, mapnik.Color("red"))
	c.get_color(255)
	c.stops[1].color
	#'''
	symbol_gdal.colorizer = c
	
	
	rule_gdal.symbols.append(symbol_gdal)
	style_gdal.rules.append(rule_gdal)
	_map.append_style("Raster Style", style_gdal)
	mlyr_gdal = mapnik.Layer('TM_images')
	mlyr_gdal.datasource = mapnik.Gdal(file=f_pct,band=1,bbox=bbox)
	mlyr_gdal.srs = '+proj=utm +zone=46 +ellps=WGS84 +units=m +no_defs '
	mlyr_gdal.styles.append('Raster Style')
	_map.layers.append(mlyr_gdal)
	
	#====
	style_gdal1 = mapnik.Style() # style object to hold rules
	rule_gdal1 = mapnik.Rule() # rule object to hold symbolizers
	symbol_gdal1 = mapnik.RasterSymbolizer()
	#symbol_gdal.mode = 'multiply'
	symbol_gdal1.opacity = 0.5
	#symbol_gdal.colorizer = mapnik.RasterColorizer(mapnik.COLORIZER_INHERIT, mapnik.Color(0,255,255))
	
	c1 = mapnik.RasterColorizer( mapnik.COLORIZER_LINEAR , mapnik.Color(0,255,0) )
	
	c1.epsilon = 0.001
	c1.add_stop(0)
	c1.add_stop(255, mapnik.COLORIZER_LINEAR, mapnik.Color("green"))
	c1.get_color(255)
	c1.stops[1].color
	#'''
	symbol_gdal1.colorizer = c1
	
	
	rule_gdal1.symbols.append(symbol_gdal1)
	style_gdal1.rules.append(rule_gdal1)
	_map.append_style("Raster Style2", style_gdal1)
	mlyr_gdal1 = mapnik.Layer('TM_images2')
	mlyr_gdal1.datasource = mapnik.Gdal(file=f_pct,band=2,bbox=bbox)
	mlyr_gdal1.srs = '+proj=utm +zone=46 +ellps=WGS84 +units=m +no_defs '
	mlyr_gdal1.styles.append('Raster Style2')
	_map.layers.append(mlyr_gdal1)
	
	#====
	#====
	style_gdal_b = mapnik.Style() # style object to hold rules
	rule_gdal_b = mapnik.Rule() # rule object to hold symbolizers
	symbol_gdal_b = mapnik.RasterSymbolizer()
	#symbol_gdal.mode = 'multiply'
	symbol_gdal_b.opacity = 0.5
	#symbol_gdal.colorizer = mapnik.RasterColorizer(mapnik.COLORIZER_INHERIT, mapnik.Color(0,255,255))
	
	c_b = mapnik.RasterColorizer( mapnik.COLORIZER_LINEAR , mapnik.Color(0,0,255) )
	
	c_b.epsilon = 0.001
	c_b.add_stop(0)
	c_b.add_stop(255, mapnik.COLORIZER_LINEAR, mapnik.Color("blue"))
	c_b.get_color(255)
	c_b.stops[1].color
	#'''
	symbol_gdal_b.colorizer = c_b
	
	
	rule_gdal_b.symbols.append(symbol_gdal_b)
	style_gdal_b.rules.append(rule_gdal_b)
	_map.append_style("Raster Style3", style_gdal_b)
	mlyr_gdal_b = mapnik.Layer('TM_images3')
	mlyr_gdal_b.datasource = mapnik.Gdal(file=f_pct,band=3,bbox=bbox)
	mlyr_gdal_b.srs = '+proj=utm +zone=46 +ellps=WGS84 +units=m +no_defs '
	mlyr_gdal_b.styles.append('Raster Style3')
	_map.layers.append(mlyr_gdal_b)
	
	#====
	
	_map.zoom_all()
	
	# Write the data to a png image called world.png the current directory
	mapnik.render_to_file(_map,f_render, 'png')


	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
Example #20
0
#   MaxScaleDenominator = INF
# Lets keep things simple and use default value, but to create a map we
# we still must provide at least one Symbolizer. Here we  want to fill countries polygons with
# greyish colour and draw outlines with a bit darker stroke.

r = mapnik2.Rule()
r.symbols.append(mapnik2.PolygonSymbolizer(mapnik2.Color('#f2eff9')))
r.symbols.append(mapnik2.LineSymbolizer(mapnik2.Color('rgb(50%,50%,50%)'),
                                        0.1))
s.rules.append(r)

# Here we have to add our style to the Map, giving it a name.
m.append_style('My Style', s)

# Here we instantiate our data layer, first by giving it a name and srs (proj4 projections string), and then by giving it a datasource.
lyr = mapnik2.Layer('world', "+proj=latlong +datum=WGS84")
# Then provide the full filesystem path to a shapefile in WGS84 or EPSG 4326 projection without the .shp extension
# A sample shapefile can be downloaded from http://mapnik-utils.googlecode.com/svn/data/world_borders.zip
lyr.datasource = mapnik2.Shapefile(
    file='/home/garel/geodata/vecteur/world/ne_110m_admin_0_countries.shp')
lyr.styles.append('My Style')

m.layers.append(lyr)
m.zoom_to_box(lyr.envelope())

# Write the data to a png image called world.png in the base directory of your user
mapnik2.render_to_file(m, '/home/garel/geodata/raster/world/world.png', 'png')

# Exit the python interpreter
exit()
Example #21
0
    pdf_surface = cairo.PDFSurface('demo.pdf', m.width, m.height)
    mapnik2.render(m, pdf_surface)
    images_.append('demo.pdf')
    pdf_surface.finish()

    postscript_surface = cairo.PSSurface('demo.ps', m.width, m.height)
    mapnik2.render(m, postscript_surface)
    images_.append('demo.ps')
    postscript_surface.finish()

else:
    print '\n\nPycairo not available...',
    if mapnik2.has_cairo():
        print ' will render Cairo formats using alternative method'

        mapnik2.render_to_file(m, 'demo.pdf')
        images_.append('demo.pdf')
        mapnik2.render_to_file(m, 'demo.ps')
        images_.append('demo.ps')
        mapnik2.render_to_file(m, 'demo.svg')
        images_.append('demo.svg')
        mapnik2.render_to_file(m, 'demo_cairo_rgb.png', 'RGB24')
        images_.append('demo_cairo_rgb.png')
        mapnik2.render_to_file(m, 'demo_cairo_argb.png', 'ARGB32')
        images_.append('demo_cairo_argb.png')

print "\n\n", len(images_), "maps have been rendered in the current directory:"

for im_ in images_:
    print "-", im_
Example #22
0
# uses mapnik 2
import mapnik2

symbolizer = mapnik2.PolygonSymbolizer(mapnik2.Color("darkgrey"))
rule = mapnik2.Rule()
rule.symbols.append(symbolizer)
style = mapnik2.Style()
style.rules.append(rule)
layer = mapnik2.Layer("mapLayer")
layer.datasource = mapnik2.Shapefile(file="/data/82945364-10m-admin-0-countries.shp")
layer.styles.append("mapStyle")
map = mapnik2.Map(2400, 1200)
map.background = mapnik2.Color("black")
map.append_style("mapStyle", style)
map.layers.append(layer)
map.zoom_all()
mapnik2.render_to_file(map, "map.png", "png")
Example #23
0
# uses mapnik 2
import mapnik2
symbolizer = mapnik2.PolygonSymbolizer(mapnik2.Color("darkgrey"))
rule = mapnik2.Rule()
rule.symbols.append(symbolizer)
style = mapnik2.Style()
style.rules.append(rule)
layer = mapnik2.Layer("mapLayer")
layer.datasource = mapnik2.Shapefile(
    file="/data/82945364-10m-admin-0-countries.shp")
layer.styles.append("mapStyle")
map = mapnik2.Map(2400, 1200)
map.background = mapnik2.Color("black")
map.append_style("mapStyle", style)
map.layers.append(layer)
map.zoom_all()
mapnik2.render_to_file(map, "map.png", "png")
Example #24
0
    pdf_surface = cairo.PDFSurface('demo.pdf', m.width,m.height)
    mapnik2.render(m, pdf_surface)
    images_.append('demo.pdf')
    pdf_surface.finish()

    postscript_surface = cairo.PSSurface('demo.ps', m.width,m.height)
    mapnik2.render(m, postscript_surface)
    images_.append('demo.ps')
    postscript_surface.finish()    

else:
    print '\n\nPycairo not available...',
    if  mapnik2.has_cairo():
        print ' will render Cairo formats using alternative method'
        
        mapnik2.render_to_file(m,'demo.pdf')
        images_.append('demo.pdf')
        mapnik2.render_to_file(m,'demo.ps')
        images_.append('demo.ps')
        mapnik2.render_to_file(m,'demo.svg')
        images_.append('demo.svg')
        mapnik2.render_to_file(m,'demo_cairo_rgb.png','RGB24')
        images_.append('demo_cairo_rgb.png')
        mapnik2.render_to_file(m,'demo_cairo_argb.png','ARGB32')
        images_.append('demo_cairo_argb.png')

print "\n\n", len(images_), "maps have been rendered in the current directory:"
    
for im_ in images_:
    print "-", im_
Example #25
0
    # merc_bbox=(mapnik.Envelope( 1095383,7066673,1103176,7074154))
    #merc_bbox=  (mapnik.Envelope( 1079799,7062935,1135458,7107904))
    #proj +to +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
    # 9.83 53.46
    # 10.1 53.62
    # 1094270.59      7068542.91
    # 1124326.86      7098514.81
    #merc_bbox= (mapnik.Box2d( 1094270,7068542,1124326,7098514))
    m.zoom_to_box(merc_bbox)
    #m.zoom_all()
    #imgx=zielgroeze_in_cm/2.54*dpi
    # render the map to an image
    sys.stdout.write('Map scale denominator: %s\n' % m.scale_denominator())
    im = mapnik.Image(imgx,imgy)
    mapnik.render(m, im)
    im.save(map_name+".png",'png')
    
    sys.stdout.write('output image to %s.png!\n' % map_name)
    
    # Note: instead of creating an image, rendering to it, and then 
    # saving, we can also do this in one step like:
    # mapnik.render_to_file(m, map_uri,'pdf')
    
    # And in Mapnik >= 0.7.0 you can also use `render_to_file()` to output
    # to Cairo supported formats if you have Mapnik built with Cairo support
    # For example, to render to pdf or svg do:
    mapnik.render_to_file(m, map_name+".pdf")
    mapnik.render_to_file(m, map_name+".svg")
    

Example #26
0
border_rule.symbols.append(lines)
district_style.rules.append(border_rule)

m.append_style('district', district_style)

district_lyr.styles.append('district')

m.layers.append(district_lyr)

ll_start = (-126.7332, 22.544, -64.9499, 51.3844)
ll_finish = (-73.967004000000102, 40.670499999999997, -73.860851000000096, 40.739339000000001)
ll = list(ll_start)

num_frames = 6000
z = 15
f = 1.0

for i in range(1, num_frames + 1):
    for j in range(0, 4):
        if i > 1:
            ll[j] = ll_finish[j] + ((ll[j]-ll_finish[j])*f)
            if f > 0.998:
                f = f - 0.00002

    c0 = prj.forward(mapnik2.Coord(ll[0], ll[1]))
    c1 = prj.forward(mapnik2.Coord(ll[2], ll[3]))
    bbox = mapnik2.Box2d(c0.x, c0.y, c1.x, c1.y)
    m.zoom_to_box(bbox)
    print "Rendering frame %d/%d" % (i, num_frames)
    mapnik2.render_to_file(m, 'frames/frame_%d.png' % i, 'png')
Example #27
0
File: tilep2.py Project: amilna/iyo
def main(argv):
	b = "-180,-90,180,90"	
	i = ""
	o = ""
	l = "-1"
	   
	try:
	  opts, args = getopt.getopt(argv,"hb:i:o:l:",["bbox","inputXml","output","layerGrid"])
	except getopt.GetoptError:
	  print 'tilep.py -b <bbox> -i <inputXml> -o <output> -l <layerGrid>'
	  sys.exit(2)	  	
	  
	for opt, arg in opts:
	  if opt == '-h':
		 print 'tilep.py -b <bbox> -i <inputXml> -o <output> -l <layerGrid>'
		 sys.exit()
	  elif opt in ("-b", "--bbox"):
		 b = arg	  
	  elif opt in ("-i", "--inputXml"):
		 i = arg      
	  elif opt in ("-o", "--output"):
		 o = arg   			
	  elif opt in ("-l", "--layerGrid"):
		 l = arg   				 				
	
	box = []
	for s in b.split(",") :
		box.append(float(s))
		
	geo_extent = Box2d(box[0],box[1],box[2],box[3])		
	
	geo_proj = Projection('+init=epsg:4326')
	merc_proj = Projection('+init=epsg:3857')	

	transform = ProjTransform(geo_proj,merc_proj)
	merc_extent = transform.forward(geo_extent)	
	
	mp = mapnik2.Map(256,256)	
	
	#sys.exit(i)		
	
	if i.find('http') >= 0:				
		xmlurl=urllib2.urlopen(i)
		xmlstr=xmlurl.read()		
		mapnik2.load_map_from_string(mp,xmlstr)		
		xmldoc = minidom.parseString(xmlstr)
	else:
		mapnik2.load_map(mp, i)	
		xmldoc = minidom.parse(i)		
		
		
	mp.zoom_to_box(merc_extent)
	
	printed = 0	
	if o == 'png':			
		im = Image(mp.width,mp.height)		
		mapnik2.render(mp,im)
		fd, path = tempfile.mkstemp()		
					    
		os.write(fd,im.tostring('png'))
		os.fsync(fd)		
		print path								
	elif o == 'json':	
		printed = 1				
	else:			
		image = o+".png"
		if not os.path.exists(os.path.dirname(image)):
			try:
				os.makedirs(os.path.dirname(image))
			except:
				pass					
		mapnik2.render_to_file(mp, image)
		if l == '-1':
			print image
	
	lgrids = []	
	if l != '-1':
		for s in l.split(",") :
			lgrids.append(int(s))
	else:
		sys.exit()
				
	itemlist = xmldoc.getElementsByTagName('Layer') 
	
	fields = []
	resolution = 4 #Pixel resolution of output.   
	printed = 0
	for ly in lgrids :	
		dat = itemlist[ly].getElementsByTagName('Datasource')[0] 
		par = dat.getElementsByTagName('Parameter')	
		for s in par :
			if s.attributes['name'].value == 'fields':			
				text = s.childNodes[0].nodeValue.encode("utf-8")			
				#print "fields "+text
				fields = text.split(",")				
			if s.attributes['name'].value == 'resolution':			
				res = s.childNodes[0].nodeValue.encode("utf-8")			
				#print "resolution "+res
				resolution = int(res)	
						
		layer_index = ly #First layer on the map - index in m.layers
		key = "__id__"  #Field used for the key in mapnik2 (should probably be unique)		
		
		enfix = ""
		if ly > 0:
			enfix = "_"+str(ly)
			
		d = mapnik2.render_grid(mp, layer_index, key, resolution, fields) #returns a dictionary		
		d = "grid("+json.dumps(d)+")"
		
		if o == 'json' and printed == 0:				
			print d
			printed = 1
		elif o == 'png':
			printed = 1				
		else:				
			print d
			f = open(o+enfix+".json",'wb')
			f.write(d)	
			f.close()
Example #28
0
# we still must provide at least one Symbolizer. Here we  want to fill countries polygons with 
# greyish colour and draw outlines with a bit darker stroke. 

r=mapnik2.Rule()
r.symbols.append(mapnik2.PolygonSymbolizer(mapnik2.Color('#f2eff9')))
r.symbols.append(mapnik2.LineSymbolizer(mapnik2.Color('rgb(50%,50%,50%)'),0.1))
s.rules.append(r)


# Here we have to add our style to the Map, giving it a name.
m.append_style('My Style',s)

# Here we instantiate our data layer, first by giving it a name and srs (proj4 projections string), and then by giving it a datasource.
lyr = mapnik2.Layer('world',"+proj=latlong +datum=WGS84")
# Then provide the full filesystem path to a shapefile in WGS84 or EPSG 4326 projection without the .shp extension
# A sample shapefile can be downloaded from http://mapnik-utils.googlecode.com/svn/data/world_borders.zip
lyr.datasource = mapnik2.Shapefile(file='/home/garel/geodata/vecteur/world/ne_110m_admin_0_countries.shp')
lyr.styles.append('My Style')


m.layers.append(lyr)
m.zoom_to_box(lyr.envelope())


# Write the data to a png image called world.png in the base directory of your user
mapnik2.render_to_file(m,'/home/garel/geodata/raster/world/world.png', 'png')

# Exit the python interpreter
exit()

Example #29
0
import mapnik2 as mapnik

mapnik.register_plugins('../') # get mongo.input

m = mapnik.Map(600,400)
m.background = mapnik.Color('white')
s = mapnik.Style()
r = mapnik.Rule()
r.symbols.append(mapnik.PointSymbolizer())
t = mapnik.TextSymbolizer(mapnik.Expression("[key]"),"DejaVu Sans Book",10,mapnik.Color('black'))
t.displacement = (15,15)
r.symbols.append(t)
s.rules.append(r)
m.append_style('style',s)
ds = mapnik.Datasource(type="mongo")
l = mapnik.Layer('test')
l.styles.append('style')
l.datasource = ds
m.layers.append(l)
m.zoom_all()
mapnik.render_to_file(m,'test.png')

Example #30
0
def mapnik_rendering(f_pct,f_vct,f_render):
	import mapnik2 as mapnik

	ref_pct = GR.geo_raster.open(f_pct)
	proj = ref_pct.projection
	tr = ref_pct.geo_transform
	width = ref_pct.width
	height = ref_pct.height
	size_p = tr[1]
	minx = tr[0]
	maxy = tr[3]
	miny = tr[3] - height * size_p
	maxx = tr[0] + width * size_p
	bbox = (minx, miny, maxx, maxy)

	#---- init
	_map = mapnik.Map(width,height)
	_map.background = mapnik.Color('black')
	#----==== raster
	style_gdal = mapnik.Style() # style object to hold rules
	rule_gdal = mapnik.Rule() # rule object to hold symbolizers
	symbol_gdal = mapnik.RasterSymbolizer()
	#symbol_gdal.opacity = 0.5
	#$symbol_gdal.colorizer = mapnik.RasterColorizer(mapnik.COLORIZER_INHERIT, mapnik.Color(255,255,255))
	c = mapnik.RasterColorizer( mapnik.COLORIZER_LINEAR , mapnik.Color(0,0,0) )
	
	c.epsilon = 0.001
	c.add_stop(0)
	c.add_stop(900, mapnik.COLORIZER_LINEAR, mapnik.Color("#F3DDB4"))
	c.add_stop(1300, mapnik.COLORIZER_LINEAR, mapnik.Color("cyan"))
	c.add_stop(2000, mapnik.COLORIZER_LINEAR, mapnik.Color("white"))
	#c.get_color(2000)
	#c.stops[1].color
	#'''
	symbol_gdal.colorizer = c
	
	rule_gdal.symbols.append(symbol_gdal)
	style_gdal.rules.append(rule_gdal)
	_map.append_style("Raster Style", style_gdal)
	mlyr_gdal = mapnik.Layer('TM_images')
	mlyr_gdal.datasource = mapnik.Gdal(file=f_pct,band=1,bbox=bbox)
	#mlyr_gdal.srs = '+proj=utm +zone=46 +ellps=WGS84 +units=m +no_defs '
	mlyr_gdal.styles.append('Raster Style')
	_map.layers.append(mlyr_gdal)
	
	#'''
	#----==== shape
	style_vct = mapnik.Style() # style object to hold rules
	rule_vct = mapnik.Rule() # rule object to hold symbolizers
	
	#==== ==== add labels
	symbol_text = mapnik.TextSymbolizer(mapnik.Expression('[Code_uniq]'), 'DejaVu Sans Book', 20, mapnik.Color('black'))
	symbol_text.halo_fill = mapnik.Color('white')
	symbol_text.halo_radius = 1
	symbol_text.avoid_edges = True 
	#symbol_text.allow_overlap = False
	symbol_text.vertical_alignment = mapnik.vertical_alignment.TOP
	symbol_text.label_placement = mapnik.label_placement.POINT_PLACEMENT #LINE_PLACEMENT # is default
	rule_vct.symbols.append(symbol_text)
	
	#==== ==== 1.add polygon
	symbol_vct = mapnik.PolygonSymbolizer(mapnik.Color('#059BFF'))
	symbol_vct.opacity = 1#0.6
	rule_vct.symbols.append(symbol_vct) # add the symbolizer to the rule object
	#==== ==== 2.add outlines
	line_symbolizer = mapnik.LineSymbolizer(mapnik.Color('black'),0.3)
	rule_vct.symbols.append(line_symbolizer) # add the symbolizer to the rule object
	
	
	style_vct.rules.append(rule_vct) # now add the rule to the style and we're done
	_map.append_style('vector',style_vct) # Styles are given names only as they are applied to the map
	ds_shp = mapnik.Shapefile(file=f_vct)
	mlyr_shp = mapnik.Layer('lakes') 

	mlyr_shp.datasource = ds_shp
	mlyr_shp.styles.append('vector')
	_map.layers.append(mlyr_shp)
	

	#'''
	_map.zoom_all()
	
	# Write the data to a png image called world.png the current directory
	mapnik.render_to_file(_map,f_render, 'png')
	print f_render


	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
Example #31
0
#!/usr/bin/env python

try:
    import mapnik2 as mapnik
except:
    import mapnik

NUM_THREADS = 4

stylesheet = 'hh_density.xml'
image = 'hh_density.png'

m = mapnik.Map(1800,1200)
mapnik.load_map(m, stylesheet)
m.zoom_all()

mapnik.render_to_file(m, image)
print "Rendered map to '%s'." % (image)
pds = mapnik2.PointDatasource()

# place scale at the bottom-center of the map
pds.add_point(label_x, label_y, 'Name', "Scale: 1:" + str(m.scale_denominator()))

# create label symbolizers
if mapnik2.mapnik_version() >= 800:
    text = mapnik2.TextSymbolizer(mapnik2.Expression('[Name]'),'DejaVu Sans Bold',12,mapnik2.Color('black'))
else:
    text = mapnik2.TextSymbolizer('Name','DejaVu Sans Bold',12,mapnik2.Color('black'))

s3 = mapnik2.Style()
r3 = mapnik2.Rule()
r3.symbols.append(text)
s3.rules.append(r3)

lyr3 = mapnik2.Layer('Memory Datasource')
lyr3.datasource = pds
lyr3.styles.append('Style')
m.layers.append(lyr3)
m.append_style('Style',s3)

###
### END scale
###

# Render Mapnik-map to png-file
mapnik2.render_to_file(m, pic_output_name, pic_output_format)

del m
Example #33
0
#!/usr/bin/env python
import mapnik2 as mapnik
m = mapnik.Map(6000,3000,"+proj=latlong +datum=WGS84")
m.background = mapnik.Color('steelblue')
s = mapnik.Style()
r=mapnik.Rule()
r.symbols.append(mapnik.PolygonSymbolizer(mapnik.Color('#f2eff9')))
r.symbols.append(mapnik.LineSymbolizer(mapnik.Color('rgb(50%,50%,50%)'),0.1))
s.rules.append(r)
m.append_style('My Style',s)
lyr = mapnik.Layer('world',"+proj=latlong +datum=WGS84")
lyr.datasource = mapnik.Shapefile(file='/opt/gdata/world_borders.shp')
lyr.styles.append('My Style')
m.layers.append(lyr)
m.zoom_to_box(lyr.envelope())
mapnik.render_to_file(m,'world.png', 'png')
Example #34
0
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
#

import mapnik2

mapfile = "tutorial2.xml"
map_output = "~/geodata/raster/world/hello_world_using_xml_config.png"
map_output = "hello_world_using_xml_config.png"

# Instantiate a map object with given width, height and spatial reference system
# m = mapnik.Map(600,300,"+proj=latlong +datum=WGS84")
m = mapnik2.Map(600, 300)

mapnik2.load_map(m, mapfile)
bbox = mapnik2.Envelope(mapnik2.Coord(-180.0, -90.0), mapnik2.Coord(180.0, 90.0))
m.zoom_to_box(bbox)

# Write the data to a png image called world.png in the base directory of your user
mapnik2.render_to_file(m, map_output)


# Exit the python interpreter
exit()
Example #35
0
    m = mapnik.Map(width, height)
    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(centrex, centrey)
    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 * (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)

    sys.stdout.write('output image to %s!\n' % output)
Example #36
0
              "Scale: 1:" + str(m.scale_denominator()))

# create label symbolizers
if mapnik2.mapnik_version() >= 800:
    text = mapnik2.TextSymbolizer(mapnik2.Expression('[Name]'),
                                  'DejaVu Sans Bold', 12,
                                  mapnik2.Color('black'))
else:
    text = mapnik2.TextSymbolizer('Name', 'DejaVu Sans Bold', 12,
                                  mapnik2.Color('black'))

s3 = mapnik2.Style()
r3 = mapnik2.Rule()
r3.symbols.append(text)
s3.rules.append(r3)

lyr3 = mapnik2.Layer('Memory Datasource')
lyr3.datasource = pds
lyr3.styles.append('Style')
m.layers.append(lyr3)
m.append_style('Style', s3)

###
### END scale
###

# Render Mapnik-map to png-file
mapnik2.render_to_file(m, pic_output_name, pic_output_format)

del m
Example #37
0
    def render_map(self,
                   lat,
                   lon,
                   angle=None,
                   angle_offset=0,
                   zoom=None,
                   overwrite=False,
                   img_width=None,
                   img_height=None,
                   zoom_to_layer=False,
                   layer_padding=10):
        """Renders map with help of mapnik

        If maps_cache is used it is first checked if image already exists in
        cache. Image name is created with self._make_name which creates name
        from lat_lon rounded to 5 decimals and width height if they are
        provided. If image exists and overwrite is False image is returned as
        ImageClip. If overwrite is True image is deleted and image is rendered
        and also returned as ImageClip.

        Parameters
        ---------
        lat : float
            Latitude in WGS84 - center point of a map (around 46 in Europe)
        lon : float
            Longitude in WGS84 - center point of a map (around 15 in Europe)
        angle : float
            If we want to rotate map. It should show where up is. AKA bearing
        angle_offset : int
            How much offset is between camera and forward direction so that
            map is correctly oriented
        zoom : float
            Mapnik zoom from 0-19 (higher number higher zoom) If we want
            different zoom then what was set in constructor
        overwrite : bool
            If we are using map cache do we want to overwrite existing images
        img_width : int
            If we want different size of map then what was set in constructor
        img_height : int
            If we want different size of map then what was set in constructor
        zoom_to_layer: bool
            If true it shows whole gpx layer in a map. lat, lon, zoom, angle are
            ignored
        layer_padding: int
            How much padding to add between edges of layer and image

        Returns
        -------
        moviepy.video.VideoClip.ImageClip, tuple
            Rendered image as clip, and tuple with x and y coordinate of center
            in pixel units. (Used to add point on current location)


        """
        map_uri = None
        width = self.map_width if img_width is None else img_width
        height = self.map_height if img_height is None else img_height
        if zoom is None:
            if self.map_zoom is None:
                raise Exception("One of map_zoom or zoom needs to be set!")
            zoom = self.map_zoom

        if angle is None:
            # spherical mercator (most common target map projection of osm data imported with osm2pgsql)
            merc = self.mercator_projection
        else:
            #Map rotation https://gis.stackexchange.com/questions/183175/rotating-90-using-two-point-equidistant-projection-with-proj4
            merc = mapnik.Projection(
                '+proj=aeqd +ellps=sphere +lat_0=90 +lon_0=-' +
                str(angle + angle_offset))
        self._lazy_init_map()
        # ensure the target map projection is mercator
        self.m.srs = merc.params()

        centre = mapnik.Coord(lon, lat)
        transform = mapnik.ProjTransform(MapnikRenderer.longlat, merc)
        merc_centre = transform.forward(centre)

        if img_width is not None and img_height is not None:
            self.m.resize(width, height)

        if not zoom_to_layer:
            # 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 * (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
            self.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
        else:
            names = ["gpx"]
            ppmm = 90.7 / 25.4
            self.m.aspect_fix_mode = mapnik.aspect_fix_mode.GROW_BBOX
            #Next for loop is from Zverik/Nik4 app
            #Calculate extent of given layers and bbox
            for layer in (l for l in self.m.layers if l.name in names):
                # it may as well be a GPX layer in WGS84
                proj = mapnik.Projection(layer.srs)
                bbox = layer.envelope() \
                        .inverse(proj).forward(self.mercator_projection)
                tscale = min((bbox.maxx - bbox.minx) / max(width, 0.01),
                             (bbox.maxy - bbox.miny) / max(height, 0.01))
                bbox.pad(layer_padding * ppmm * tscale)
                bounds = bbox

# Note: aspect_fix_mode is only available in Mapnik >= 0.6.0
        self.m.zoom_to_box(bounds)

        center_pixel_coord = self.m.view_transform().forward(merc_centre)
        #print ("img_width: {} map_width:{} width:{}".format(img_width, self.map_width, width))
        if self.maps_cache is not None:
            zoom_name = zoom if self.zoom_changeable else None
            fn = self._make_name(lat, lon, width, height, zoom_name,
                                 zoom_to_layer)
            #print ("Rendering " + fn)
            map_uri = os.path.join(self.maps_cache, "{}.png".format(fn))
            #If we don't want to overwrite and file already exists skip map rendering
            if not overwrite and os.path.isfile(map_uri):
                return ImageClip(map_uri), (center_pixel_coord.x,
                                            center_pixel_coord.y)


#If we want to overwrite and file exists we remove file
            if overwrite and os.path.isfile(map_uri):
                os.remove(map_uri)

        #start = time.perf_counter()
        if self.maps_cache is not None:
            mapnik.render_to_file(self.m, map_uri)
            map_data = map_uri
        else:
            #Renders map to image in memory saves it to buffer and reads in numpy
            im = mapnik.Image(self.m.width, self.m.height)
            mapnik.render(self.m, im)
            #im.save("/tmp/tmp.png", 'png256')
            #Saving image to bytes buffer needs to be nonpalletted image otherwise it needs
            #to be converted to RGB when reading in numpy anyways
            string_image = im.tostring('png32')
            buffer = BytesIO(string_image)
            #with open("/tmp/tmp1.png", "wb") as o:
            #o.write(buffer.getvalue())
            pil_image = ImagePIL.open(buffer)
            #print (pil_image.format, pil_image.mode, pil_image.size,
            #pil_image.palette)
            map_data = np.asarray(pil_image)
            #map_data = "/tmp/tmp.png"
        if img_width is not None and img_height is not None:
            self.m.resize(self.map_width, self.map_height)

        #print ("render took %r s" % (time.perf_counter()-start,))
        return ImageClip(map_data), (center_pixel_coord.x,
                                     center_pixel_coord.y)