def render(qs,options): kwargs = {} if options: if ';' in options: for item in options.split(';'): if ':' in item: k,v = item.split(':') kwargs[k] = v width = int(kwargs.get('width',600)) height = int(kwargs.get('height',600)) #field = kwargs.get('field',None) if hasattr(qs,'_meta'): # it looks like a model qs = qs.objects.all() m = mapnik.Map(width,height) m.aspect_fix_mode = mapnik.aspect_fix_mode.GROW_CANVAS adapter = PostgisLayer(qs) lyr = adapter.to_mapnik() sty = adapter.get_default_style() lyr.styles.append('style') m.append_style('style',sty) #m.background = mapnik.Color('green') m.srs = lyr.srs m.layers.append(lyr) m.zoom_all() #print mapnik.save_map_to_string(m) mod = qs.query.get_meta().module_name # TODO - need way to properly cache vs. always overwriting... name = '%s_%s_%s_%s.png' % (mod,width,height,random()) map_graphic = os.path.join(graphics,name) mapnik.render_to_file(m,str(map_graphic)) url = os.path.join(settings.MEDIA_URL,'mapgraphics',name) return mark_safe(force_unicode('<img src="%s" />' % smart_str(url)))
def show(self, **kwargs): timeit = kwargs.get('timeit') if timeit: start = time.time() # todo - we should check for postgis support, and otherwise # use the MemoryDatasource lyr_adapter = PostgisLayer(self) lyr_adapter.show(**kwargs) if timeit: elapsed = (time.time() - start) / 60 print 'render time: %s seconds' % elapsed
def show(self,**kwargs): timeit = kwargs.get('timeit') if timeit: start = time.time() # todo - we should check for postgis support, and otherwise # use the MemoryDatasource lyr_adapter = PostgisLayer(self) lyr_adapter.show(**kwargs) if timeit: elapsed = (time.time() - start)/60 print 'render time: %s seconds' % elapsed
def draw_map(uids, user, width, height, autozoom=False, bbox=None, show_extent=False, map_name='default'): """Display a map with the study region geometry. """ map = get_object_or_404(MapConfig, mapname=map_name) if not width: width = map.default_width if not height: height = map.default_height mapfile = str(map.mapfile.path) # Create a blank image and map draw = mapnik.Image(width, height) m = mapnik.Map(width, height) # load_map is NOT thread safe (?) # load_map_from_string appears to work #mapnik.load_map(m, mapfile) xmltext = open(mapfile).read() mapnik.load_map_from_string(m, xmltext) log.debug("Completed load_map_from_string(), Map object is %r" % m) # Create the mapnik layers features = get_features(uids, user) for model, pks in features: try: geomfield = model.mapnik_geomfield() except AttributeError: geomfield = 'geometry_final' if geomfield not in [str(x.name) for x in model._meta.fields]: continue if not issubclass(model, FeatureCollection): try: style = model.mapnik_style() except AttributeError: style = default_style() style_name = str('%s_style' % model.model_uid()) # tsk mapnik cant take unicode m.append_style(style_name, style) adapter = PostgisLayer(model.objects.filter(pk__in=pks), field_name=geomfield) lyr = adapter.to_mapnik() lyr.styles.append(style_name) m.layers.append(lyr) # Grab the bounding coordinates and set them if specified # first, assume default image extent x1, y1 = map.default_x1, map.default_y1 x2, y2 = map.default_x2, map.default_y2 if not bbox and autozoom and features and len(features) > 0: x1, y1, x2, y2 = auto_extent(features, map.default_srid) if bbox: try: x1, y1, x2, y2 = [float(x) for x in bbox.split(',')] except: pass bbox = mapnik.Envelope(mapnik.Coord(x1, y1), mapnik.Coord(x2, y2)) if show_extent and features and len(features) > 0: # Shows a bounding box for the extent of all specified features # Useful for overview maps x1, y1, x2, y2 = auto_extent(features, map.default_srid) ps = mapnik.PolygonSymbolizer(mapnik.Color('#ffffff')) ps.fill_opacity = 0.8 ls = mapnik.LineSymbolizer(mapnik.Color('#ff0000'), 2.0) r = mapnik.Rule() r.symbols.append(ps) r.symbols.append(ls) extent_style = mapnik.Style() extent_style.rules.append(r) m.append_style('extent_style', extent_style) lyr = mapnik.Layer("Features Extent") bbox_sql = """ (select 1 as id, st_setsrid(st_makebox2d(st_point(%s,%s),st_point(%s,%s)), %s) as geometry_final) as aoi """ % (x1, y1, x2, y2, map.default_srid) lyr.datasource = mapnik.PostGIS( host=connection.settings_dict['HOST'], user=connection.settings_dict['USER'], password=connection.settings_dict['PASSWORD'], dbname=connection.settings_dict['NAME'], table=bbox_sql, geometry_field='geometry_final', estimate_extent='False', extent='%s,%s,%s,%s' % (x1, y1, x2, y2)) lyr.styles.append('extent_style') m.layers.append(lyr) # Render image and send out the response m.zoom_to_box(bbox) mapnik.render(m, draw) img = draw.tostring('png') # if testing via django unit tests, close out the connection conn = connection.settings_dict if conn['NAME'] != settings_dbname: del m return img
def draw_map(uids, user, width, height, autozoom=False, bbox=None, show_extent=False, map_name='default'): """Display a map with the study region geometry. """ # if testing via django unit tests, close out the connection conn = connection.settings_dict testing = False if conn['NAME'] != settings_dbname: testing = True map = get_object_or_404(MapConfig,mapname=map_name) if not width: width = map.default_width if not height: height = map.default_height mapfile = str(map.mapfile.path) # Create a blank image and map draw = mapnik.Image(width,height) m = mapnik.Map(width,height) # load_map is NOT thread safe (?) # load_map_from_string appears to work #mapnik.load_map(m, mapfile) xmltext = open(mapfile).read() # Replace mediaroot xmltext = xmltext.replace("[[MEDIA_ROOT]]",settings.MEDIA_ROOT) mapnik.load_map_from_string(m, xmltext) log.debug("Completed load_map_from_string(), Map object is %r" % m) # Create the mapnik layers features = get_features(uids,user) for model, pks in features: try: geomfield = model.mapnik_geomfield() except AttributeError: geomfield = 'geometry_final' if geomfield not in [str(x.name) for x in model._meta.fields]: continue if not issubclass(model, FeatureCollection): try: style = model.mapnik_style() except AttributeError: style = default_style() style_name = str('%s_style' % model.model_uid()) # tsk mapnik cant take unicode m.append_style(style_name, style) if testing: adapter = PostgisLayer(model.objects.filter(pk__in=pks), field_name=geomfield, persist_connection=False) else: adapter = PostgisLayer(model.objects.filter(pk__in=pks), field_name=geomfield) lyr = adapter.to_mapnik() lyr.styles.append(style_name) m.layers.append(lyr) # Grab the bounding coordinates and set them if specified # first, assume default image extent x1, y1 = map.default_x1, map.default_y1 x2, y2 = map.default_x2, map.default_y2 if not bbox and autozoom and features and len(features) > 0: x1, y1, x2, y2 = auto_extent(features, map.default_srid) if bbox: try: x1, y1, x2, y2 = [float(x) for x in bbox.split(',')] except: pass bbox = mapnik.Box2d(mapnik.Coord(x1,y1), mapnik.Coord(x2,y2)) if show_extent and features and len(features) > 0: # Shows a bounding box for the extent of all specified features # Useful for overview maps x1, y1, x2, y2 = auto_extent(features, map.default_srid) ps = mapnik.PolygonSymbolizer(mapnik.Color('#ffffff')) ps.fill_opacity = 0.8 ls = mapnik.LineSymbolizer(mapnik.Color('#ff0000'),2.0) r = mapnik.Rule() r.symbols.append(ps) r.symbols.append(ls) extent_style = mapnik.Style() extent_style.rules.append(r) m.append_style('extent_style', extent_style) lyr = mapnik.Layer("Features Extent") bbox_sql = """ (select 1 as id, st_setsrid(st_makebox2d(st_point(%s,%s),st_point(%s,%s)), %s) as geometry_final) as aoi """ % (x1,y1,x2,y2,map.default_srid) lyr.datasource = mapnik.PostGIS(host=connection.settings_dict['HOST'], user=connection.settings_dict['USER'], password=connection.settings_dict['PASSWORD'], dbname=connection.settings_dict['NAME'], table=bbox_sql, geometry_field='geometry_final', estimate_extent=False, persist_connection=not testing, extent='%s,%s,%s,%s' % (x1,y1,x2,y2)) lyr.styles.append('extent_style') m.layers.append(lyr) # Render image and send out the response m.zoom_to_box(bbox) mapnik.render(m, draw) img = draw.tostring('png') if testing: del m return img
def tileLayer(request, version, shapefile_id, zoom, x, y): try: if version != "1.0": raise Http404 try: shapefile = Shapefile.objects.get(id=shapefile_id, created_by=request.user) except Shapefile.DoesNotExist: raise Http404 zoom = int(zoom) x = int(x) y = int(y) if zoom < 0 or zoom > MAX_ZOOM_LEVEL: raise Http404 xExtent = _unitsPerPixel(zoom) yExtent = _unitsPerPixel(zoom) minLong = x * xExtent - 20037508.34 minLat = y * yExtent - 20037508.34 maxLong = minLong + xExtent maxLat = minLat + yExtent if (minLong < -20037508.34 or maxLong > 20037508.34 or minLat < -20037508.34 or maxLat > 20037508.34): raise Http404 #create de mapnik.map object map = mapnik.Map( TILE_WIDTH, TILE_HEIGHT, "+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0.0 +k=1.0 +units=m +nadgrids=@null +no_defs +over" ) map.background = mapnik.Color("#f2f3f7") #defining the feature layer geometryField = utils.calcGeometryField(shapefile.geom_type) field = "'NOM'" field2 = "'CODE'" query = '(select ' + geometryField + ', attribute_value->' + field + ' as label, id_relat from "shapefile_feature" where' + ' shapefile_id in (' + str( shapefile.id) + ')) as geom' feature = Feature.objects.filter(shapefile__id=shapefile_id).geojson() adapter = DjLayer(feature) lyr = adapter.to_mapnik() lyr.srs = "+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0.0 +k=1.0 +units=m +nadgrids=@null +no_defs +over" m = mapnik.Map( TILE_WIDTH, TILE_HEIGHT, "+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0.0 +k=1.0 +units=m +nadgrids=@null +no_defs +over" ) ## datasource = mapnik.PostGIS(user=dbSettings['USER'], ## password=dbSettings['PASSWORD'], ## dbname=dbSettings['NAME'], ## port=5433, ## table=query, ## srid=3857, ## geometry_field=geometryField, ## simplify_geometries=True, ## geometry_table='"shapefile_feature"') ## featureLayer = mapnik.Layer("featureLayer") ## featureLayer.srs = "+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0.0 +k=1.0 +units=m +nadgrids=@null +no_defs +over" ## featureLayer.datasource = datasource ## featureLayer.styles.append("featureLayerStyle") ## #defining the feature layer styles rule = mapnik.Rule() if shapefile.geom_type in ["Point", "MultiPoint"]: rule.symbols.append(mapnik.PointSymbolizer()) elif shapefile.geom_type in ["LineString", "MultiLineString"]: rule.symbols.append( mapnik.LineSymbolizer(mapnik.Color("#000000"), 0.5)) elif shapefile.geom_type in ["Polygon", "MultiPolygon"]: rule.symbols.append( mapnik.PolygonSymbolizer(mapnik.Color("#f7edee"))) rule.symbols.append( mapnik.LineSymbolizer(mapnik.Color("#000000"), 0.5)) ## ## label = mapnik.TextSymbolizer(mapnik.Expression('[label]'), 'DejaVu Sans Book', 10, mapnik.Color('black')) ## label.halo_fill = mapnik.Color('white') ## label.halo_radius = 4 ## label.label_placement = mapnik.label_placement.INTERIOR_PLACEMENT ## label.allow_overlap = True ## label.avoid_edges = True ## rule.symbols.append(label) style = mapnik.Style() style.rules.append(rule) lyr.styles.append('name') ## ## #add new feature to the map m.append_style("name", style) m.layers.append(lyr) ## map.layers.append(featureLayer) #rendering the map tile mapnik.save_map( m, "../tilestache/%s/%s.xml" % (str(request.user), str(shapefile.filename))) config = { "cache": { "name": "Disk", "path": "../tilestache/%s" % (request.user), "umask": "0000", "dirs": "portable" }, "layers": { shapefile.filename: { "provider": { "name": "mapnik", "mapfile": "../tilestache/%s/%s.xml" % (request.user, shapefile.filename) }, "projection": "spherical mercator" } } } # like http://tile.openstreetmap.org/1/0/0.png #coord = ModestMaps.Core.Coordinate(y, x, zoom) path = "/%s/%s/%s/%s.png" % (shapefile.filename, zoom, x, y) config = TileStache.Config.buildConfiguration(config) #type, bytes = TileStache.getTile(config.layers[shapefile.filename], coord, 'png') type, bytes = TileStache.requestHandler(config, path) return HttpResponse(bytes, mimetype="image/png") except: traceback.print_exc() return HttpResponse("")
def tileLayer(request, version, shapefile_id, zoom, x, y): try: if version != "1.0": raise Http404 try: shapefile = Shapefile.objects.get(id=shapefile_id, created_by=request.user) except Shapefile.DoesNotExist: raise Http404 zoom = int(zoom) x = int(x) y = int(y) if zoom < 0 or zoom > MAX_ZOOM_LEVEL: raise Http404 xExtent = _unitsPerPixel(zoom) yExtent = _unitsPerPixel(zoom) minLong = x * xExtent - 20037508.34 minLat = y * yExtent - 20037508.34 maxLong = minLong + xExtent maxLat = minLat + yExtent if (minLong < -20037508.34 or maxLong > 20037508.34 or minLat < -20037508.34 or maxLat > 20037508.34): raise Http404 #create de mapnik.map object map = mapnik.Map(TILE_WIDTH, TILE_HEIGHT, "+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0.0 +k=1.0 +units=m +nadgrids=@null +no_defs +over") map.background = mapnik.Color("#f2f3f7") #defining the feature layer geometryField = utils.calcGeometryField(shapefile.geom_type) field = "'NOM'" field2 = "'CODE'" query = '(select ' + geometryField + ', attribute_value->' + field +' as label, id_relat from "shapefile_feature" where' + ' shapefile_id in (' + str(shapefile.id) + ')) as geom' feature = Feature.objects.filter(shapefile__id=shapefile_id).geojson() adapter = DjLayer(feature) lyr = adapter.to_mapnik() lyr.srs = "+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0.0 +k=1.0 +units=m +nadgrids=@null +no_defs +over" m = mapnik.Map(TILE_WIDTH, TILE_HEIGHT, "+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0.0 +k=1.0 +units=m +nadgrids=@null +no_defs +over") ## datasource = mapnik.PostGIS(user=dbSettings['USER'], ## password=dbSettings['PASSWORD'], ## dbname=dbSettings['NAME'], ## port=5433, ## table=query, ## srid=3857, ## geometry_field=geometryField, ## simplify_geometries=True, ## geometry_table='"shapefile_feature"') ## featureLayer = mapnik.Layer("featureLayer") ## featureLayer.srs = "+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0.0 +k=1.0 +units=m +nadgrids=@null +no_defs +over" ## featureLayer.datasource = datasource ## featureLayer.styles.append("featureLayerStyle") ## #defining the feature layer styles rule = mapnik.Rule() if shapefile.geom_type in ["Point", "MultiPoint"]: rule.symbols.append(mapnik.PointSymbolizer()) elif shapefile.geom_type in ["LineString", "MultiLineString"]: rule.symbols.append(mapnik.LineSymbolizer(mapnik.Color("#000000"), 0.5)) elif shapefile.geom_type in ["Polygon", "MultiPolygon"]: rule.symbols.append(mapnik.PolygonSymbolizer(mapnik.Color("#f7edee"))) rule.symbols.append(mapnik.LineSymbolizer(mapnik.Color("#000000"), 0.5)) ## ## label = mapnik.TextSymbolizer(mapnik.Expression('[label]'), 'DejaVu Sans Book', 10, mapnik.Color('black')) ## label.halo_fill = mapnik.Color('white') ## label.halo_radius = 4 ## label.label_placement = mapnik.label_placement.INTERIOR_PLACEMENT ## label.allow_overlap = True ## label.avoid_edges = True ## rule.symbols.append(label) style = mapnik.Style() style.rules.append(rule) lyr.styles.append('name') ## ## #add new feature to the map m.append_style("name", style) m.layers.append(lyr) ## map.layers.append(featureLayer) #rendering the map tile mapnik.save_map(m, "../tilestache/%s/%s.xml" % (str(request.user), str(shapefile.filename))) config = { "cache": { "name": "Disk", "path": "../tilestache/%s" % (request.user), "umask": "0000", "dirs": "portable"}, "layers": { shapefile.filename: { "provider": {"name": "mapnik", "mapfile": "../tilestache/%s/%s.xml" % (request.user, shapefile.filename)}, "projection": "spherical mercator" } } } # like http://tile.openstreetmap.org/1/0/0.png #coord = ModestMaps.Core.Coordinate(y, x, zoom) path = "/%s/%s/%s/%s.png" % (shapefile.filename,zoom,x,y) config = TileStache.Config.buildConfiguration(config) #type, bytes = TileStache.getTile(config.layers[shapefile.filename], coord, 'png') type, bytes = TileStache.requestHandler(config, path) return HttpResponse(bytes, mimetype="image/png") except: traceback.print_exc() return HttpResponse("")