def render_tile(self, tile_uri, x, y, z, buffer_size): tile = (x, y) c0, c1 = self.calcTileCoordinates(tile, z) tile_extent = (c0.x, c0.y, c1.x, c1.y) #dest_file = "WebGen_WPS_file.xml" #folder = "/home/klammer/Software/Quickly/TileGen/tilegen/data/media/" #test = makeWPSfile(tile_extent, folder+dest_file) #if test > 0: # sendFile(dest_file, folder) # 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 = buffer_size # Render image with default Agg renderer im = mapnik.Image(render_size, render_size) mapnik.render(self.m, im) im.save(tile_uri, 'png256')
def mouseReleaseEvent(self, event): if event.button() == Qt.LeftButton: self.drag = False self.endDragPos = event.pos() if self.toolMode == 3: QApplication.setOverrideCursor(QCursor(Qt.OpenHandCursor)) cx = int(0.5 * self.map.width) cy = int(0.5 * self.map.height) dpos = self.endDragPos - self.startDragPos self.map.pan(cx - dpos.x(), cy - dpos.y()) self.updateMap() if self.toolMode == 1: env = mapnik.Envelope(self.startDragPos.x(), self.endDragPos.y(), self.endDragPos.x(), self.startDragPos.y()) self.map.zoom_to_box(self.map.view_transform().backward(env)) self.updateMap() if self.toolMode == 2: self.scale = True w = self.startDragPos.x() - self.endDragPos.x() h = self.startDragPos.y() - self.endDragPos.y() self.zoomPos = QPoint(self.endDragPos.x() + w / 2, self.endDragPos.y() + h / 2) self.total_scale *= (((self.width() / w) + (self.height() / h)) / 2) * 0.8 self.updateMap()
def set_center_and_radius(self, lon, lat, radius=None, geographic=True): coords = mapnik.Coord(lon, lat) box = mapnik.Envelope(coords.x - radius, coords.y - radius, coords.x + radius, coords.y + radius) if geographic and not self.proj_obj.geographic: box = box.forward(self.proj_obj) self.zoom_to_box(box)
def render_tile(mapfile, tile_uri, x, y, z): m = mapnik.Map(256, 256) # Load style XML mapnik.load_map(m, mapfile, True) # Obtain <Map> projection prj = mapnik.Projection(m.srs) # Projects between tile pixel co-ordinates and LatLong (EPSG:4326) tileproj = GoogleProjection(z+1) # 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 = tileproj.fromPixelToLL(p0, z); l1 = tileproj.fromPixelToLL(p1, z); # Convert to map projection (e.g. mercator co-ords EPSG:900913) c0 = prj.forward(mapnik.Coord(l0[0],l0[1])) c1 = prj.forward(mapnik.Coord(l1[0],l1[1])) # Bounding box for the tile bbox = mapnik.Envelope(c0.x,c0.y, c1.x,c1.y) render_size = 256 m.resize(render_size, render_size) m.zoom_to_box(bbox) m.buffer_size = 128 # Render image with default Agg renderer im = mapnik.Image(render_size, render_size) mapnik.render(m, im) im.save(tile_uri, 'png256')
def updateMap(self): self.timer.stop() if self.drag: cx = int(0.5 * self.map.width) cy = int(0.5 * self.map.height) dpos = self.endDragPos - self.startDragPos self.map.pan(cx - dpos.x(), cy - dpos.y()) self.drag = False elif self.scale: ma = QMatrix() ma.translate(self.zoomPos.x(), self.zoomPos.y()) ma.scale(self.total_scale, self.total_scale) ma.translate(-self.zoomPos.x(), -self.zoomPos.y()) rect = ma.mapRect(QRectF(0, 0, self.map.width, self.map.height)) env = mapnik.Envelope(rect.left(), rect.bottom(), rect.right(), rect.top()) self.map.zoom_to_box(self.map.view_transform().backward(env)) self.total_scale = 1.0 self.scale = False im = mapnik.Image(self.map.width, self.map.height) mapnik.render(self.map, im) self.qim.loadFromData(QByteArray(im.tostring('png'))) self.update()
def __std_render(self, parameters, filename): 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') imgwidth = math.trunc(parameters.pagewidth / inch * parameters.dpi) imgheight = math.trunc(parameters.pageheight / inch * parameters.dpi) m = mapnik.Map(imgwidth, imgheight) mapnik.load_map(m, parameters.mapstyle) m.srs = merc.params() if hasattr(mapnik, 'Box2d'): bbox = mapnik.Box2d(self.minlon, self.minlat, self.maxlon, self.maxlat) else: bbox = mapnik.Envelope(self.minlon, self.minlat, self.maxlon, self.maxlat) transform = mapnik.ProjTransform(longlat, merc) merc_bbox = transform.forward(bbox) m.zoom_to_box(merc_bbox) #pdfprint = mapnik.printing.PDFPrinter(pagesize=[ (pagewidthcm+2) / 100, (pageheightcm+2) / 100], resolution=dpi) #pdfprint.render_map(m, filename) #context = pdfprint.get_context() #pdfprint.render_scale(m, ctx=context) #pdfprint.render_legend(m, ctx=context, attribution="(c) OpenStreetMap contributors") mapnik.render_to_file(m, filename, parameters.output_format)
def render(mapfile, dst_img, mm_width, mm_height, bounds, dpi=300, nztm_style='style-nztm.xml'): ''' Render an image with mapnik from an *.xml style file ''' # create a version of the source style document in NZTM set_projection(mapfile, dst_path=nztm_style) # convert mm to pixels pixel_width = mm_to_pixels(mm_width, dpi) pixel_height = mm_to_pixels(mm_height, dpi) print('Rendering {} @ {} x {} pixels @ {} dpi'.format( dst_img, pixel_width, pixel_height, dpi)) # create the output map m = mapnik.Map(pixel_width, pixel_height) # load style rules & set bounding box mapnik.load_map(m, nztm_style) bbox = mapnik.Envelope(mapnik.Coord(bounds[0], bounds[1]), mapnik.Coord(bounds[2], bounds[3])) m.zoom_to_box(bbox) # render map & save mapnik.render_to_file(m, dst_img) print('Rendered {} @ {} x {} pixels'.format(dst_img, pixel_width, pixel_height))
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')
def save(self, out, format): if format not in ('PNG'): raise KnownUnknown('We only saves .png tiles, not "%s"' % format) if not self.data['has_stuff']: im = Image.new('RGBA', (self.width, self.height)) im.save(out, 'PNG') return fh, tmpfile = tempfile.mkstemp('.json') os.write(fh, json.dumps(self.data['geojson'])) os.close(fh) map = mapnik.Map(0, 0) map.srs = '+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' datasource = mapnik.Ogr(base=os.path.dirname(tmpfile), file=os.path.basename(tmpfile), layer='OGRGeoJSON') os.unlink(tmpfile) lyr = mapnik.Layer('xapi_raster') lyr.srs = '+proj=latlong +datum=WGS84' lyr.datasource = datasource style = mapnik.Style() rule = mapnik.Rule() if self.data['filltype'] == 'line': fill = mapnik.Color(str(self.data['fill'])) # TO DO: make me a config flag # rule.symbols.append(mapnik.LineSymbolizer(fill, 1.0)) rule.symbols.append(mapnik.LineSymbolizer(fill, 3.0)) style.rules.append(rule) else: fill = mapnik.Color(str(self.data['fill'])) rule.symbols.append(mapnik.PolygonSymbolizer(fill)) style.rules.append(rule) map.append_style('xapi_raster', style) lyr.styles.append('xapi_raster') map.layers.append(lyr) xmin, ymin, xmax, ymax = self.data['bbox'] env = mapnik.Envelope(xmin, ymin, xmax, ymax) map.width = self.width map.height = self.height map.zoom_to_box(env) img = mapnik.Image(self.width, self.height) mapnik.render(map, img) img = Image.fromstring('RGBA', (self.width, self.height), img.tostring()) img.save(out, 'PNG')
def render(self): """ Renders the request, returning a binary in the specified format. """ map_size = self.get_size() map, data_layers = self.factory.getMap(self.map_definition, map_size) geojson_file = tempfile.NamedTemporaryFile(suffix='.json') try: # write the JSON to a temporary file geojson_file.write(str(self)) geojson_file.flush() # find the layer definition(s) in the map xml and update it # to point to our temporary file geojson_dir, geojson_filename = os.path.split(geojson_file.name) for layer in data_layers: layer.datasource = mapnik.Ogr(base=geojson_dir, file=geojson_filename, layer='OGRGeoJSON') # set the map extent if self.bbox_image: # specified extent map_bbox = mapnik.Envelope( mapnik.Coord(self.bbox_image[0], self.bbox_image[1]), mapnik.Coord(self.bbox_image[2], self.bbox_image[3])) map.zoom_to_box(map_bbox) else: # zoom to the extent of our data layers extent = data_layers[0].envelope() for l in data_layers[1:]: extent += layer.envelope() map.zoom_to_box(extent) # if we have a buffer, apply it if self.bbox_image_buffer: extent = map.envelope() units = self.bbox_image_buffer[1].lower() if units == 'map': # map-units buffer = self.bbox_image_buffer[0] extent.expand_to_include(extent.minx - buffer, extent.miny - buffer) extent.expand_to_include(extent.maxx + buffer, extent.maxy + buffer) elif units == 'px': # pixels map.buffer_size = self.bbox_image_buffer[0] extent = map.buffered_envelope() else: self.L.warn("Unknown bbox_image_buffer units: %s", units) # reapply our new extent map.zoom_to_box(extent) # render it return self._render_surface(map, map_size) finally: geojson_file.close()
def renderTile(self, tile): import mapnik, StringIO import PIL.Image if self.mapnik: m = self.mapnik else: if self.fonts: engine = mapnik.FontEngine.instance() for font in self.fonts: engine.register_font(font) # Init it as 0,0 m = mapnik.Map(0, 0) mapnik.load_map(m, self.mapfile) if self.projection: m.srs = self.projection # Restrict layer list, if requested if self.layers and self.layers != self.name: layers = self.layers.split(",") for layer_num in range(len(m.layers) - 1, -1, -1): l = m.layers[layer_num] if l.name not in layers: del m.layers[layer_num] if self.debug: print >> sys.stderr, "Removed layer %s loaded from %s, not in list: %s" % ( l.name, self.mapfile, layers) # this will insure that it gets cached in mod_python self.mapnik = m # Set the mapnik size to match the size of the current tile m.width = tile.size()[0] m.height = tile.size()[1] bbox = tile.bounds() bbox = mapnik.Envelope(bbox[0], bbox[1], bbox[2], bbox[3]) m.zoom_to_box(bbox) im = mapnik.Image(*tile.size()) mapnik.render(m, im) if hasattr(im, 'tostring'): data = im.tostring() elif hasattr(mapnik, 'rawdata'): data = mapnik.rawdata(im) else: raise Exception( "Something is wrong: your version of Mapnik can't create a string from an image." ) im = PIL.Image.fromstring('RGBA', tile.size(), data) buffer = StringIO.StringIO() im.save(buffer, self.extension) buffer.seek(0) tile.data = buffer.read() return tile.data
def render_tile(self) -> bytes: """ generate tile or load it from redis cache :return: tile as png image in bytes format """ tile_name: str = '/tmp/{}-{}-{}-{}.png'.format( self.request_date_to_string(), self.zoom, self.x_pixel, self.y_pixel) if env.bool("CACHE", default=False): # try if exists to get cache style_xml try: tile_content = cache.get(tile_name) if tile_content: return tile_content except (redis.exceptions.ConnectionError, redis.exceptions.DataError) as exc: print(exc) os.chdir(os.environ['STYLE_PATH']) map: mapnik.Map = mapnik.Map(self.width, self.height) mapnik.load_map_from_string(map, self.generate_date_style_xml()) prj: mapnik.Projection = 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 +wktext +no_defs +over" ) p0 = self.from_px_to_ll( (self.width * self.x_pixel, self.height * (self.y_pixel + 1)), self.zoom) p1 = self.from_px_to_ll( (self.width * (self.x_pixel + 1), self.height * self.y_pixel), self.zoom) c0 = prj.forward(mapnik.Coord(p0[0], p0[1])) c1 = prj.forward(mapnik.Coord(p1[0], p1[1])) bbox: mapnik.Envelope = mapnik.Envelope(c0.x, c0.y, c1.x, c1.y) map.zoom_to_box(bbox) image: mapnik.Image = mapnik.Image(self.width, self.height) mapnik.render(map, image) # todo generate tile without save it to hdd mapnik.render_to_file(map, tile_name) tile_content: bytes = open(tile_name, 'rb').read() os.remove(tile_name) if env.bool("CACHE", default=False): # upload style_xml file to redis cache cache.set(tile_name, tile_content, ex=env.int("CAHCE_EXPIRE_TIME", default=3600)) return tile_content
def set_center_and_zoom(self, lon, lat, level=0, geographic=True): coords = mapnik.Coord(lon, lat) if geographic and not self.proj_obj.geographic: coords = coords.forward(self.proj_obj) w, h = self.width, self.height res = self.get_scale_for_zoom_level(level) box = mapnik.Envelope(coords.x - 0.5 * w * res, coords.y - 0.5 * h * res, coords.x + 0.5 * w * res, coords.y + 0.5 * h * res) self.zoom_to_box(box)
def xyz_to_envelope(self,x,y,zoom, tms_style=False, count=1): """ Convert XYZ to mapnik.Envelope """ # flip y to match TMS spec if tms_style: y = (2**zoom-1) - y ll = (x * self.size,(y + count) * self.size) ur = ((x + count) * self.size, y * self.size) minx,miny = self.px_to_ll(ll,zoom) maxx,maxy = self.px_to_ll(ur,zoom) lonlat_bbox = mapnik.Envelope(minx,miny,maxx,maxy) env = mercator.forward(lonlat_bbox) return env
def render(parameters): if not parameters.verbose: mapnik.logger.set_severity(getattr(mapnik.severity_type, 'None')) 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') imgwidth = math.trunc(parameters.pagewidth / inch * parameters.dpi) imgheight = math.trunc(parameters.pageheight / inch * parameters.dpi) m = mapnik.Map(imgwidth, imgheight) mapnik.load_map(m, parameters.mapstyle) mapnik.load_map(m, parameters.hikingmapstyle) m.srs = merc.params() if hasattr(mapnik, 'Box2d'): bbox = mapnik.Box2d(parameters.minlon, parameters.minlat, parameters.maxlon, parameters.maxlat) else: bbox = mapnik.Envelope(parameters.minlon, parameters.minlat, parameters.maxlon, parameters.maxlat) transform = mapnik.ProjTransform(longlat, merc) merc_bbox = transform.forward(bbox) m.zoom_to_box(merc_bbox) for gpxfile in parameters.gpxfiles: gpxlayer = mapnik.Layer('GPXLayer') gpxlayer.datasource = mapnik.Ogr(file=gpxfile, layer='tracks') gpxlayer.styles.append('GPXStyle') m.layers.append(gpxlayer) if parameters.temptrackfile: overviewlayer = mapnik.Layer('OverviewLayer') overviewlayer.datasource = mapnik.Ogr(file=parameters.temptrackfile, layer='tracks') overviewlayer.styles.append('GPXStyle') m.layers.append(overviewlayer) if parameters.tempwaypointfile: waypointlayer = mapnik.Layer('WaypointLayer') waypointlayer.datasource = mapnik.Ogr(file=parameters.tempwaypointfile, layer='waypoints') waypointlayer.styles.append('WaypointStyle') m.layers.append(waypointlayer) mapnik.render_to_file( m, parameters.basefilename + "." + parameters.output_format, parameters.output_format, parameters.scale_factor)
def __std_render(self, parameters, tempwaypointfile, filename): 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') imgwidth = math.trunc(self.get_page_width() / inch * parameters.dpi) imgheight = math.trunc(self.get_page_height() / inch * parameters.dpi) m = mapnik.Map(imgwidth, imgheight) mapnik.load_map(m, parameters.mapstyle) mapnik.load_map(m, parameters.hikingmapstyle) m.srs = merc.params() if hasattr(mapnik, 'Box2d'): bbox = mapnik.Box2d(self.minlon, self.minlat, self.maxlon, self.maxlat) else: bbox = mapnik.Envelope(self.minlon, self.minlat, self.maxlon, self.maxlat) transform = mapnik.ProjTransform(longlat, merc) merc_bbox = transform.forward(bbox) m.zoom_to_box(merc_bbox) for gpxfile in parameters.gpxfiles: gpxlayer = mapnik.Layer('GPXLayer') gpxlayer.datasource = mapnik.Ogr(file=gpxfile, layer='tracks') gpxlayer.styles.append('GPXStyle') m.layers.append(gpxlayer) if parameters.waypt_distance > 0: waypointlayer = mapnik.Layer('WaypointLayer') waypointlayer.datasource = mapnik.Ogr(file=tempwaypointfile, layer='waypoints') waypointlayer.styles.append('WaypointStyle') m.layers.append(waypointlayer) #pdfprint = mapnik.printing.PDFPrinter(pagesize = [ 0.21, 0.297 ], \ # margin = 0.005, resolution = parameters.dpi) #context = pdfprint.get_cairo_context() #pdfprint.render_scale(m, ctx=context) #pdfprint.render_legend(m, ctx=context, attribution="(c) OpenStreetMap contributors") #pdfprint.render_map(m, filename) #im = mapnik.Image(m.width, m.height) #mapnik.render(m, im) #im.save(filename, parameters.output_format) mapnik.render_to_file(m, filename, parameters.output_format)
def pure_tile_rendering(args): tile_dir = args[0] mapfile = args[1] maxZoom = args[2] tile_uri = args[3] x = args[4] y = args[5] z = args[6] #not needed anymore, as the mapnik.map is sent directly to the function m = mapnik.Map(256, 256) # Load style XML mapnik.load_map_from_string(m, mapfile) # Obtain <Map> projection prj = mapnik.Projection(m.srs) # Projects between tile pixel co-ordinates and LatLong (EPSG:4326) tileproj = GoogleProjection(maxZoom + 1) tile = (x, y) #print 'Tile: ', tile # Calculate pixel positions of bottom-left & top-right p0 = (tile[0] * 256, (tile[1] + 1) * 256) p1 = ((tile[0] + 1) * 256, tile[1] * 256) # Convert to LatLong (EPSG:4326) l0 = tileproj.fromPixelToLL(p0, z) l1 = tileproj.fromPixelToLL(p1, z) # Convert to map projection (e.g. mercator co-ords EPSG:900913) c0 = prj.forward(mapnik.Coord(l0[0], l0[1])) c1 = prj.forward(mapnik.Coord(l1[0], l1[1])) #c0, c1 = calcTileCoordinates(tile, z) tile_extent = (c0.x, c0.y, c1.x, c1.y) # Bounding box for the tile bbox = mapnik.Envelope(c0.x, c0.y, c1.x, c1.y) m.zoom_to_box(bbox) # Render image with default Agg renderer im = mapnik.Image(m.height, m.width) mapnik.render(m, im) im.save(tile_uri, 'png256') return m.scale() / 0.00028
def get_bbox(self): # Calculate pixel positions of bottom-left & top-right p0 = (self.mtx0 * TILE_SIZE, (self.mty0 + self.metatile) * TILE_SIZE) p1 = ((self.mtx0 + self.metatile) * TILE_SIZE, self.mty0 * TILE_SIZE) # Convert to LatLong (EPSG:4326) l0 = self.tileproj.fromPixelToLL(p0, self.zoom); l1 = self.tileproj.fromPixelToLL(p1, self.zoom); # 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) return bbox
def get_bbox(self, x, y, z): # Calculate pixel positions of bottom-left & top-right p0 = (x * self.render_size, (y + 1) * self.render_size) p1 = ((x + 1) * self.render_size, y * self.render_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: return mapnik.Box2d(c0.x, c0.y, c1.x, c1.y) else: return mapnik.Envelope(c0.x, c0.y, c1.x, c1.y)
def mapnik_tiles(request): global MAP_CACHE w, h = int(request.GET['WIDTH']), int(request.GET['HEIGHT']) mime = request.GET['FORMAT'] if not MAP_CACHE: MAP_CACHE = MapCache(request) env = map(float, request.GET['BBOX'].split(',')) tile = MAP_CACHE.map tile.buffer_size = 128 tile.resize(w, h) tile.zoom_to_box(mapnik.Envelope(*env)) draw = mapnik.Image(tile.width, tile.height) mapnik.render(tile, draw) image = draw.tostring(str(mime.split('/')[1])) response = HttpResponse() response['Content-length'] = len(image) response['Content-Type'] = mime response.write(image) return response
def render_tile(m, z, x, y, scale, dir, type, lock=None, threadnum=None): n = 2**z n2 = n / 2 x2n = x - n2 y2n = (n - y - 1) - n2 tilesize = float(scale) / float(n) bbox = [ tilesize * x2n, tilesize * y2n, tilesize * (x2n + 1), tilesize * (y2n + 1) ] pdir = dir + "/" + str(z) + "/" + str(x) if lock: lock.acquire() print "Thread #%u: z=%u x=%u y=%u -> (%f,%f,%f,%f)" % ( threadnum, z, x, y, bbox[0], bbox[1], bbox[2], bbox[3]) if not os.path.exists(pdir): os.makedirs(pdir) lock.release() else: if not os.path.exists(pdir): os.makedirs(pdir) print "z=%u x=%u y=%u -> (%f,%f,%f,%f)" % (z, x, y, bbox[0], bbox[1], bbox[2], bbox[3]) if mapnik.Box2d: e = mapnik.Box2d(*bbox) else: e = mapnik.Envelope(*bbox) # zoom map to bounding box m.zoom_to_box(e) file = dir + "/" + str(z) + "/" + str(x) + "/" + str(y) + "." + type s = mapnik.Image(256, 256) mapnik.render(m, s) view = s.view(0, 0, 256, 256) view.save(file, type)
def simpleRendering(image, stylesheet, extent): mapfile = stylesheet map_uri = image imgx = 256 imgy = 256 m = mapnik.Map(imgx, imgy) mapnik.load_map(m, mapfile) #print 'simple Rendering' #print m.layers 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')
def render_tile(self, tile_dir, x, y, z): # Calculate pixel positions of bottom-left & top-right p0 = (x * 256 * aggregate, (y + 1) * 256 * aggregate) p1 = ((x + 1) * 256 * aggregate, y * 256 * aggregate) # 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 * aggregate 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) for i in range(0, aggregate): # check if we have directories in place str_x = "%s" % (x * aggregate + i) zoom = "%s" % z if not os.path.isdir(tile_dir + zoom + '/' + str_x): os.mkdir(tile_dir + zoom + '/' + str_x) for j in range(0, aggregate): view = im.view(i * 256, j * 256, 256, 256) #print(i*256,j*256,(i+1)*256,(j+1)*256) str_y = "%s" % (y * aggregate + j) tile_uri = tile_dir + zoom + '/' + str_x + '/' + str_y + '.png' view.save(tile_uri, 'png256')
def render(self, bbox, width=None, height=None): """ Render the specified tile with Mapnik """ width = width or self.tilesize height = height or self.tilesize if not self._mapnik: self._mapnik = mapnik.Map(width, height) # Load style XML mapnik.load_map(self._mapnik, self.stylefile, True) # Obtain <Map> projection self._prj = mapnik.Projection(self._mapnik.srs) # Convert to map projection assert len(bbox) == 4, _( "Provide a bounding box tuple (minx, miny, maxx, maxy)") c0 = self._prj.forward(mapnik.Coord(bbox[0], bbox[1])) c1 = self._prj.forward(mapnik.Coord(bbox[2], bbox[3])) # 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) self._mapnik.resize(width, height) self._mapnik.zoom_to_box(bbox) self._mapnik.buffer_size = 128 # Render image with default Agg renderer tmpfile = NamedTemporaryFile(delete=False) im = mapnik.Image(width, height) mapnik.render(self._mapnik, im) im.save(tmpfile.name, 'png256') # TODO: mapnik output only to file? tmpfile.close() content = open(tmpfile.name).read() os.unlink(tmpfile.name) return content
def __call__(self, req): """ """ print print 'Using %s' % self.mapfile print bbox = req.get('BBOX') env = map(float, bbox.split(',')) bbox = mapnik.Envelope(*env) if self.singletile: self.mapnik_map.width, self.mapnik_map.height = int( req.get('WIDTH')), int(req.get('HEIGHT')) self.mapnik_map.zoom_to_box(bbox) draw = mapnik.Image(self.mapnik_map.width, self.mapnik_map.height) mapnik.render(self.mapnik_map, draw) image = draw.tostring('png256') response = z.Response(image, status=200, mimetype=self.mime) response.content_length = len(image) return response
def render_meta(self, m, style, x, y, z, sz): # Calculate pixel positions of bottom-left & top-right p0 = (x * 256, (y + sz) * 256) p1 = ((x + sz) * 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[style].forward(mapnik.Coord(l0[0], l0[1])) c1 = self.prj[style].forward(mapnik.Coord(l1[0], l1[1])) # Bounding box for the meta-tile bbox = mapnik.Envelope(c0.x, c0.y, c1.x, c1.y) render_size = 256 * sz m.resize(render_size, render_size) m.zoom_to_box(bbox) m.buffer_size = 128 im = self.render_with_agg(m, render_size) #im = self.render_with_cairo(m, render_size) return self.split_meta_image(im, sz)
def generate_image(self, xml, filename, ext, ftype, ll, dx, dy, res, verbose, force): print "generate_image:", xml, filename mapfile = xml merc = "+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" latlon = "+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs" m = mapnik.Map(dx, dy) mapnik.load_map(m, mapfile) # Override projection defined in mapfile m.srs = latlon #m.srs = merc # Calculate projected boundaries prj = mapnik.Projection(m.srs) c0 = prj.forward(mapnik.Coord(ll[0], ll[1])) c1 = prj.forward(mapnik.Coord(ll[2], ll[3])) # Apply bounding box bbox = mapnik.Envelope(c0.x, c0.y, c1.x, c1.y) m.zoom_to_box(bbox) # Render image im = mapnik.Image(dx, dy) mapnik.render(m, im) view = im.view(0, 0, dx, dy) png_file = filename + ext #".png" if force or not os.path.isfile(png_file): if verbose: print("saving " + png_file) view.save(png_file, ftype)
def render_tile(tile_uri, x, y, z): #print tile_uri,":",z,x,y # 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 = tileproj.fromPixelToLL(p0, z) l1 = tileproj.fromPixelToLL(p1, z) # Convert to map projection (e.g. mercator co-ords EPSG:900913) c0 = prj.forward(mapnik.Coord(l0[0], l0[1])) c1 = prj.forward(mapnik.Coord(l1[0], l1[1])) bb = mapnik.Envelope(c0.x, c0.y, c1.x, c1.y) render_size = 256 m.resize(render_size, render_size) m.zoom_to_box(bb) m.buffer_size = 128 # Render image with default Agg renderer im = mapnik.Image(render_size, render_size) mapnik.render(m, im) im.save(tile_uri, 'png256')
def draw_district_outline(statefp, state, district, shpfeature, map_size, contextmap) : # Create an image with district outlines and shading over the parts of the map # in other districts or other states. Also compute our desired bounding box. # Get bounding box of this map, which will be a little larger than the boudning box of the district. long_min, long_max, lat_min, lat_max = shpfeature.GetGeometryRef().GetEnvelope() margin = 0.06 if contextmap : margin = 1.5 d_long = long_max-long_min d_lat = lat_max-lat_min long_min -= d_long*margin long_max += d_long*margin lat_min -= d_lat*margin lat_max += d_lat*margin # Choose an aspect ratio for the final image that is a good match for # the shape of the district. We have two choices. We could use nice-looking # aspect ratios or we could use aspect ratios that match common sizes of # paper so that the map can be printed nicely. good_aspect_ratios = [ (3.0, 3.0/1.0), # 8.5x17 tabloid landscape (1.5, 16.0/9.0), # HD widescreen (1.25, 11.0/8.5), # 8.5x11 letter landscape (1/1.25, 1.0/1.0), # square (1/1.5, 8.5/11.0), # 8.5x11 letter portrait (0, 8.5/17.0), # 8.5x17 tabloid portrait ] for threshold, ratio in good_aspect_ratios: if d_long/d_lat > threshold: if ratio > 1.0: map_width = int(ratio * map_size) map_height = map_size else: map_width = map_size map_height = int(map_size / ratio) break # Create a map. m = mapnik.Map(map_width, map_height, output_projection) # Center to the projected coordinates. bounds = (mapnik.Projection(output_projection).forward( mapnik.Projection(census_shapefile_projection).inverse(mapnik.Coord(long_min, lat_min)) ), mapnik.Projection(output_projection).forward( mapnik.Projection(census_shapefile_projection).inverse(mapnik.Coord(long_max, lat_max)) )) m.zoom_to_box(mapnik.Envelope(bounds[0].x, bounds[0].y, bounds[1].x, bounds[1].y)) if not contextmap : # Add a layer for counties and ZCTAs. # TODO: These should really be generated with the map tile layer # so that the labels don't hit each other. for layer, featurename, labelfontsize, labelcolor, border in ( ("county", "NAME", map_size/40, mapnik.Color('rgb(70%,20%,20%)'), True), ("zcta510", "ZCTA5CE10", map_size/60, mapnik.Color('rgb(40%,40%,80%)'), False), ): s = mapnik.Style() r = mapnik.Rule() if border: p = mapnik.LineSymbolizer(labelcolor, map_size/300) p.stroke.opacity = .3 p.stroke.add_dash(.1, .1) r.symbols.append(p) r.symbols.append(mapnik.TextSymbolizer(mapnik.Expression('[%s]' % featurename), mapnik_label_font, labelfontsize, labelcolor)) s.rules.append(r) m.append_style('%s Style' % layer, s) lyr = mapnik.Layer('world', census_shapefile_projection) lyr.datasource = mapnik.Shapefile(file=sys.argv[1] + "/tl_2013_us_%s.shp" % layer) lyr.styles.append('%s Style' % layer) m.layers.append(lyr) # Draw shading and numbering for the other districts. district_outline_color = mapnik.Color('rgb(100%,75%,25%)') s = mapnik.Style() r = mapnik.Rule() p = mapnik.PolygonSymbolizer(mapnik.Color('rgb(70%,70%,70%)')) p.fill_opacity = .55 r.symbols.append(p) r.filter = mapnik.Filter("([CD113FP] <> '" + district + "' || [STATEFP] <> '" + statefp + "') && [CD113FP] != 'ZZ'") t = mapnik.TextSymbolizer(mapnik.Expression('[CD113FP]'), mapnik_label_font, map_size/15, district_outline_color) t.halo_radius = map_size/120 r.symbols.append(t) s.rules.append(r) # Draw the outlines of districts. Use a hard thin outline to be exact plus # a faded wider outline for strength. r = mapnik.Rule() p = mapnik.LineSymbolizer(district_outline_color, 2) r.symbols.append(p) p = mapnik.LineSymbolizer(district_outline_color, map_size/140) p.stroke.opacity = .35 r.symbols.append(p) s.rules.append(r) m.append_style('Other Districts Style',s) lyr = mapnik.Layer('world', census_shapefile_projection) lyr.datasource = mapnik.Shapefile(file=sys.argv[1] + "/tl_2013_us_cd113.shp") lyr.styles.append('Other Districts Style') m.layers.append(lyr) im = mapnik.Image(map_width, map_height) mapnik.render(m, im) env = m.envelope() env = ( mapnik.Projection(output_projection).inverse(mapnik.Coord(env[0], env[1])), mapnik.Projection(output_projection).inverse(mapnik.Coord(env[2], env[3])) ) return im, env
map_uri = options.name m = mapnik.Map(img[0], img[1]) mapnik.load_map(m, mapfile) # Override projection defined in mapfile m.srs = latlon #m.srs = merc # Calculate projected boundaries prj = mapnik.Projection(m.srs) c0 = prj.forward(mapnik.Coord(bounds[0], bounds[1])) c1 = prj.forward(mapnik.Coord(bounds[2], bounds[3])) # Apply bounding box bbox = mapnik.Envelope(c0.x, c0.y, c1.x, c1.y) m.zoom_to_box(bbox) # Render image im = mapnik.Image(img[0], img[1]) mapnik.render(m, im) view = im.view(0, 0, img[0], img[1]) if force or not os.path.isfile(map_uri): if verbose: print("saving " + map_uri) view.save(map_uri) if verbose: print 'output image to %s!\n' % map_uri