def generate(self): mapnik.load_map(self.mapnikObj, self.style) self.layer = mapnik.Layer('Provinces') self.layer.srs = self.spatialReference[self.srs] #sym = mapnik.PointSymbolizer("imgs/marker-icon.png", "png", 16, 16) self.layer.datasource = mapnik.CSV(inline='wkt\n"' + self.wkt + '"', filesize_max=500) self.layer.styles.append(self.geom_type) self.mapnikObj.layers.append(self.layer) if self.bbox == 0: self.mapnikObj.zoom_all() # Render map mapnik.render(self.mapnikObj, self.mapnikImg) # Save image to files image_complete_name = self.image_name + '.' + self.imgType self.mapnikImg.save(image_complete_name, self.imgType) # true-colour RGBA image_file = open(image_complete_name, 'rb') image_out = image_file.read() image_file.close() os.remove(image_complete_name) if self.deleteStyle: os.remove(self.style) return image_out
def create_map(dir, roi_file): width = 800 height = 800 config = get_instance() lats = config.bbox["lats"] lons = config.bbox["lons"] buff = 1 bbox = mapnik.Box2d(lons[0] - buff, lats[0] - buff, lons[1] + buff, lats[1] + buff) map = mapnik.Map(width, height) plot_data_dir = os.path.join(os.path.dirname(__file__), "plot_data") mapnik.load_map(map, os.path.join(plot_data_dir, "ci_test.xml")) roi_csv_file = os.path.join(os.path.dirname(__file__), dir, roi_file) roi_csv_ds = mapnik.CSV(file=roi_csv_file) roi_layer = mapnik.Layer("roi_pred") roi_layer.datasource = roi_csv_ds roi_layer_style = create_roi_output_style("prediction") map.append_style("roi_layer_style", roi_layer_style) roi_layer.styles.append("roi_layer_style") map.layers.append(roi_layer) map.zoom_to_box(bbox) mapnik.render_to_file(map, os.path.join(dir, '%s.png' % roi_file), 'png')
def setup_base_layer(m): styled_map = add_base_style(m) # layer setup zcsv = mapnik.CSV(file=zipcode_file_path) layer = mapnik.Layer('chicago') layer.datasource = zcsv layer.styles.append('My Style') styled_map.layers.append(layer) return m
def setup_highlight_layer(m,zip_code): highlighted_map = setup_highlight_styles(m) try: row = [x for x in zipcode_csv if x['ZIP'] == zip_code][0] except: import ipdb; ipdb.set_trace() data = ','.join(row.keys()) + '\r\n' + ','.join(['"' + row[k] + '"' for k in row.keys()]) csv_data = mapnik.CSV(inline=data) layer = mapnik.Layer('c2') layer.datasource = csv_data layer.styles.append('highlight') highlighted_map.layers.append(layer) return m
def generate(self): mapnik.load_map(self.mapnikObj, self.style) self.layer = mapnik.Layer('Provinces') self.layer.srs = self.spatialReference[self.srs] #sym = mapnik.PointSymbolizer("imgs/marker-icon.png", "png", 16, 16) self.layer.datasource = mapnik.CSV(inline='wkt\n"' + self.wkt + '"', filesize_max=500) # to use other datasources. The GeoJSON as datasource doesn't generate the image and we don't know why. #self.layer.datasource = mapnik.PostGIS( # host=settings.DATABASES['default']['HOST'], # user=settings.DATABASES['default']['USER'], # password=settings.DATABASES['default']['PASSWORD'], # dbname=settings.DATABASES['default']['NAME'], # table=self.table_name) #self.layer.datasource = mapnik.GeoJSON(file=self.geojsonfile) #self.layer.datasource = mapnik.Shapefile(file=self.geometry, encoding='latin1') self.layer.styles.append(self.geom_type) self.mapnikObj.layers.append(self.layer) if self.bbox == 0: self.mapnikObj.zoom_all() # Render map mapnik.render(self.mapnikObj, self.mapnikImg) # Save image to files image_complete_name = self.image_name + '.' + self.imgType self.mapnikImg.save(image_complete_name, self.imgType) # true-colour RGBA image_file = open(image_complete_name, 'rb') image_out = image_file.read() image_file.close() os.remove(image_complete_name) if self.deleteStyle: os.remove(self.style) return image_out
def render_static(request, height=None, width=None, format='png', background='satellite', bounds=None, center=None, render_srid=3857): # width and height width = int(width) height = int(height) if width > settings.MAX_IMAGE_DIMENSION or \ height > settings.MAX_IMAGE_DIMENSION or \ width <= 1 or height <= 1: logging.debug("Invalid size") return HttpResponseBadRequest( "Invalid image size, both dimensions must be in range %i-%i" % (1, settings.MAX_IMAGE_DIMENSION)) # image format if format not in IMAGE_FORMATS: logging.error("unknown image format %s" % format) return HttpResponseBadRequest( "Unknown image format, available formats: " + ", ".join(IMAGE_FORMATS)) if format.startswith('png'): mimetype = 'image/png' elif format.startswith('jpeg'): mimetype = 'image/jpeg' # bounds bounds_box = None if bounds: bounds_components = bounds.split(',') if len(bounds_components) != 4: return HttpResponseBadRequest( "Invalid bounds, must be 4 , separated numbers") bounds_components = [float(f) for f in bounds_components] if not (-180 < bounds_components[0] < 180) or not (-180 < bounds_components[2] < 180): logging.error("x out of range %f or %f" % (bounds_components[0], bounds_components[2])) return HttpResponseBadRequest( "x out of range %f or %f" % (bounds_components[0], bounds_components[2])) if not (-90 < bounds_components[1] < 90) or not (-90 < bounds_components[3] < 90): logging.error("y out of range %f or %f" % (bounds_components[1], bounds_components[3])) return HttpResponseBadRequest( "y out of range %f or %f" % (bounds_components[1], bounds_components[3])) ll = Point(bounds_components[0], bounds_components[1], srid=4326) ll.transform(render_srid) ur = Point(bounds_components[2], bounds_components[3], srid=4326) ur.transform(render_srid) bounds_box = mapnik.Box2d(ll.x, ll.y, ur.x, ur.y) elif center: center_components = center.split(',') if len(center_components) != 3: return HttpResponseBadRequest() lon = float(center_components[0]) lat = float(center_components[1]) zoom = int(center_components[2]) # todo calc bounds from center and zoom # baselayer if background not in settings.BASE_LAYERS and background != 'none': return HttpResponseNotFound("Background not found") # GeoJSON post data if request.method == "POST" and len(request.body): input_data = json.loads(request.body) else: input_data = None if not bounds and not center and not input_data: return HttpResponseBadRequest( "Bounds, center, or post data is required.") # initialize map m = mapnik.Map(width, height) m.srs = '+init=epsg:' + str(render_srid) # add a tile source as a background if background != "none": background_file = settings.BASE_LAYERS[background] background_style = mapnik.Style() background_rule = mapnik.Rule() background_rule.symbols.append(mapnik.RasterSymbolizer()) background_style.rules.append(background_rule) m.append_style('background style', background_style) tile_layer = mapnik.Layer('background') tile_layer.srs = '+init=epsg:' + str(render_srid) tile_layer.datasource = mapnik.Gdal(base=settings.BASE_LAYER_DIR, file=background_file) tile_layer.styles.append('background style') m.layers.append(tile_layer) # add features from geojson if input_data and input_data['type'] == "Feature": features = [input_data] elif input_data and input_data['type'] == "FeatureCollection": if 'features' not in input_data: return HttpResponseBadRequest() features = input_data['features'] else: features = [] logging.debug("Adding %d features to map" % len(features)) geometries = [] point_features = [] fid = 0 for feature in features: if 'geometry' not in feature: logging.debug("feature does not have geometry") return HttpResponseBadRequest("Feature does not have a geometry") if 'type' not in feature['geometry']: logging.debug("geometry does not have type") return HttpResponseBadRequest("Geometry does not have a type") fid += 1 style_name = str(fid) if feature['geometry']['type'] == 'Point': point_features.append(feature) elif feature['geometry']['type'] in ('LineString', 'MultiLineString'): if feature['geometry']['type'] == 'LineString': geos_feature = LineString(feature['geometry']['coordinates']) elif feature['geometry']['type'] == 'MultiLineString': rings = feature['geometry']['coordinates'] rings = [[(c[0], c[1]) for c in r] for r in rings] if len(rings) == 1: geos_feature = LineString(rings[0]) else: linestrings = [] for ring in rings: try: linestrings.append(LineString(ring)) except Exception, e: logging.error("Error adding ring: %s", e) geos_feature = MultiLineString(linestrings) geos_feature.srid = 4326 geos_feature.transform(render_srid) geometries.append(geos_feature) style = mapnik.Style() line_rule = mapnik.Rule() style_dict = None if 'style' in feature: style_dict = feature['style'] elif 'properties' in feature: style_dict = feature['properties'] line_rule.symbols.append(line_symbolizer(style_dict)) style.rules.append(line_rule) m.append_style(style_name, style) wkt = geos_feature.wkt line_layer = mapnik.Layer(style_name + ' layer') line_layer.datasource = mapnik.CSV(inline='wkt\n' + '"' + wkt + '"') line_layer.styles.append(style_name) line_layer.srs = '+init=epsg:' + str(render_srid) m.layers.append(line_layer) elif feature['geometry']['type'] == 'Polygon': geos_feature = GEOSGeometry(json.dumps(feature['geometry'])) geos_feature.srid = 4326 geos_feature.transform(render_srid) geometries.append(geos_feature) style = mapnik.Style() rule = mapnik.Rule() style_dict = None if 'style' in feature: style_dict = feature['style'] elif 'properties' in feature: style_dict = feature['properties'] rule.symbols.append(polygon_symbolizer(style_dict)) rule.symbols.append(line_symbolizer(style_dict)) style.rules.append(rule) m.append_style(style_name, style) wkt = geos_feature.wkt layer = mapnik.Layer(style_name + ' layer') layer.datasource = mapnik.CSV(inline='wkt\n' + '"' + wkt + '"') layer.styles.append(style_name) layer.srs = '+init=epsg:' + str(render_srid) m.layers.append(layer)
point_rule = mapnik.Rule() point_symbolizer = mapnik.PointSymbolizer() point_rule.symbols.append(point_symbolizer) point_style.rules.append(point_rule) m.append_style('point_style', point_style) csv = 'wkt\n' for feature in point_features: geos_feature = Point(feature['geometry']['coordinates']) geos_feature.srid = 4326 geos_feature.transform(render_srid) geometries.append(geos_feature) csv += '"' + geos_feature.wkt + '"\n' point_layer = mapnik.Layer('point layer') point_layer.datasource = mapnik.CSV(inline=csv) point_layer.styles.append('point_style') point_layer.srs = '+init=epsg:' + str(render_srid) m.layers.append(point_layer) # bounds not in url, calculate from data if not bounds_box: geometry_collection = GeometryCollection(geometries) minx, miny, maxx, maxy = geometry_collection.extent buffer_size = .2 x_buffer_size = ((maxx - minx) * buffer_size) y_buffer_size = ((maxy - miny) * buffer_size) if x_buffer_size == 0: # this can happen if there is only 1 point feature x_buffer_size = 1000 if y_buffer_size == 0:
def service_get_wms_of_shape(request, width, height, bbox, presentationlayer_id, legend_id, timestep): """ width = int height = int bbox = tuple """ pl = get_object_or_404(PresentationLayer, pk=presentationlayer_id) if legend_id == -1: legend_id = pl.presentationtype.default_legend_id #presentation_dir = Setting.objects.get( key = 'presentation_dir' ).value #################### set up map ################################### log.debug('start setting up map ' + str(datetime.datetime.now())) m = mapnik.Map(width, height) spherical_mercator = ( '+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 ' '+y_0=0 +k=1.0 +units=m +nadgrids=@null +no_defs +over') m.srs = spherical_mercator m.background = mapnik.Color('transparent') #p = mapnik.Projection(spherical_mercator) log.debug('start setting up legend ' + str(datetime.datetime.now())) #################### set up legend ################################### mpl = cache.get('legend_' + str(legend_id)) if mpl == None: sdl = get_object_or_404(ShapeDataLegend, pk=legend_id) if pl.presentationtype.geo_type in [ PresentationType.GEO_TYPE_POLYGON, PresentationType.GEO_TYPE_LINE, PresentationType.GEO_TYPE_POINT ]: sm = SymbolManager('media/flooding_presentation/symbols/') mpl = MapnikPointLegend(sdl, sm) cache.set('legend_' + str(legend_id), mpl, 300) fields = mpl.get_presentationtype_fields() log.debug('start setting up lijntje ' + str(datetime.datetime.now())) #################### supportive layers ################################### if SupportLayers.objects.filter( presentationtype=pl.presentationtype).count() > 0: supportive_layers = (pl.presentationtype.supported_presentationtype. supportive_presentationtype.all()) sl = mapnik.Style() rule_l = mapnik.Rule() rule_stk = mapnik.LineSymbolizer() rule_stk.stroke = mapnik.Color(3, 158, 137) rule_stk.stroke_linecap = mapnik._mapnik.stroke_linecap.ROUND_CAP rule_stk.stroke_width = 2.0 rule_l.symbols.append(rule_stk) sl.rules.append(rule_l) m.append_style('Line Style', sl) for spt in supportive_layers: log.debug('supportive layer with id: ' + str(spt.id)) # warning! works only for flooding scenarios if pl.scenario_set.count() > 0: scenario = pl.scenario_set.get() layers = PresentationLayer.objects.filter(presentationtype=spt, scenario=scenario) if len(layers) > 0: log.debug( 'supportive layer found for this presentationlayer') layer = layers[0] lyrl = mapnik.Layer('lines', spherical_mercator) lyrl.datasource = mapnik.Shapefile( file=external_file_location( layer.presentationshape.geo_source.file_location)) lyrl.styles.append('Line Style') m.layers.append(lyrl) #################### read data ################################### #read source and attach values log.debug('ready setting up map ' + str(datetime.datetime.now())) log.debug('start reading point cache ' + str(datetime.datetime.now())) points = cache.get('model_nodes_' + str(presentationlayer_id) + '_' + str(timestep) + '_' + str(legend_id)) log.debug('ready reading point cache ' + str(datetime.datetime.now())) if points is None: log.debug('start reading points from shape and his file ' + str(datetime.datetime.now())) points = [] drv = ogr.GetDriverByName('ESRI Shapefile') shapefile_name = external_file_location( pl.presentationshape.geo_source.file_location) ds = drv.Open(shapefile_name) layer = ds.GetLayer() has_his_file_field = False has_geo_file_field = False geo_fields = [] log.debug('fields are: ' + str(fields)) for nr in fields: field = fields[nr] if field.source_type == Field.SOURCE_TYPE_VALUE_SOURCE_PARAM: has_his_file_field = True his_field = field #only his files yet supported. read needed data log.debug('start reading hiscache' + str(datetime.datetime.now())) his = cache.get('his_' + str(presentationlayer_id)) log.debug('ready reading hiscache' + str(datetime.datetime.now())) if his == None: log.debug('read hisfile' + str(datetime.datetime.now())) zip_name = external_file_location( pl.presentationshape.value_source.file_location) input_file = ZipFile(zip_name, "r") if pl.presentationtype.geo_source_filter: filename = pl.presentationtype.geo_source_filter else: filename = input_file.filelist[0].filename his = HISFile(Stream(input_file.read(filename))) input_file.close() log.debug('ready reading hisfile' + str(datetime.datetime.now())) cache.set('his_' + str(presentationlayer_id), his, 3000) values = his.get_values_timestep_by_index( his.get_parameter_index(his_field.name_in_source), timestep) elif field.source_type == Field.SOURCE_TYPE_GEO_SOURCE_COL: has_geo_file_field = True geo_fields.append(field) else: log.debug('field source type ' + field.source_type + ' not yet supported') if layer.GetFeatureCount() > 0: feature = layer.next() id_index = feature.GetFieldIndex('id') for field in geo_fields: field.index_nr = feature.GetFieldIndex( str(field.name_in_source)) layer.ResetReading() ############################# place features in the right 'legend box' for feature in layer: point = feature.geometry() input_dict = {} if has_his_file_field: #get id form geosource, needed for reading hisfile id = (pl.presentationtype.value_source_id_prefix + str(feature.GetField(id_index).strip())) if pl.presentationtype.absolute: try: input_dict[his_field.name_in_source] = abs( values.get(id, None)) if values.get(id, None) > 1: pass except TypeError: input_dict[his_field.name_in_source] = None else: input_dict[his_field.name_in_source] = values.get(id, None) if has_geo_file_field: for field in geo_fields: input_dict[field.name_in_source] = feature.GetField( field.index_nr) rule_name = mpl.get_rule_name(input_dict) if pl.presentationtype.geo_type == 3: x = (point.GetX(0) + point.GetX(1)) / 2 y = (point.GetY(0) + point.GetY(1)) / 2 else: x = point.GetX() y = point.GetY() #rule_name = str('1_neerslag_64_0010000100_24x24_0_0') points.append((x, y, "NAME", rule_name)) # Clean up ds.Destroy() log.debug('ready reading points form shape en his file ' + str(datetime.datetime.now())) cache.set( 'model_nodes_' + str(presentationlayer_id) + '_' + str(timestep) + '_' + str(legend_id), points, 300) log.debug('start making memory datasource ' + str(datetime.datetime.now())) lyr = mapnik.Layer('Points', spherical_mercator) m.append_style('Points legend', mpl.get_style()) next_id = 1 csv = 'id,NAME,wkt\n' for x, y, name, rule_name in points: wkt = '"POINT(%0.1f %0.1f)"' % (x, y) csv += "{0},{1},{2}\n".format(next_id, rule_name, wkt) next_id += 1 ds = mapnik.CSV(inline=csv) lyr.datasource = ds log.debug('finish making memory datasource ' + str(datetime.datetime.now())) lyr.styles.append('Points legend') m.layers.append(lyr) if presentationlayer_id in [62007, 62008]: m = mapnik.Map(width, height) spherical_mercator = mapnik.Projection( '+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 ' '+y_0=0 +k=1.0 +units=m +nadgrids=@null +no_defs +over') m.srs = spherical_mercator m.background = mapnik.Color('transparent') sl = mapnik.Style() rule_l = mapnik.Rule() rule_stk = mapnik.LineSymbolizer() rule_stk.stroke = mapnik.Color(3, 158, 137) rule_stk.stroke_linecap = mapnik._mapnik.stroke_linecap.ROUND_CAP rule_stk.stroke_width = 2.0 rule_l.symbols.append(rule_stk) sl.rules.append(rule_l) m.append_style('Line Style2', sl) scenario = pl.scenario_set.get() layers = PresentationLayer.objects.filter(presentationtype=spt, scenario=scenario) log.debug('supportive layer found for this presentationlayer') rds = mapnik.Projection( "+proj=sterea +lat_0=52.15616055555555 +lon_0=5.38763888888889 " "+k=0.999908 +x_0=155000 +y_0=463000 +ellps=bessel " "+towgs84=565.237,50.0087,465.658,-0.406857,0.350733," "-1.87035,4.0812 +units=m +no_defs") lyrl = mapnik.Layer('lines', rds) # Commented out, variable 'presentation_dir' doesn't exist so this # cannot work. -- RG20120621 # lyrl.datasource = mapnik.Shapefile( # file=external_file_location( # str(presentation_dir + '\\' + # pl.presentationshape.geo_source.file_location))) lyrl.styles.append('Line Style2') m.layers.append(lyrl) ##################### render map ############################# m.zoom_to_box(mapnik.Envelope(*bbox)) # lyrl.envelope log.debug('start render map ' + str(datetime.datetime.now())) img = mapnik.Image(width, height) mapnik.render(m, img) log.debug('ready render map ' + str(datetime.datetime.now())) log.debug('start PIL ' + str(datetime.datetime.now())) # you can use this if you want te modify image with PIL imgPIL = Image.fromstring('RGBA', (width, height), img.tostring()) #imgPIL = imgPIL.convert('RGB') buffer = StringIO.StringIO() imgPIL.save(buffer, 'png') # ,transparency = 10 buffer.seek(0) response = HttpResponse(buffer.read()) log.debug('end PIL ' + str(datetime.datetime.now())) response['Content-type'] = 'image/png' log.debug('ready sending map ' + str(datetime.datetime.now())) return response
def generate_geometric_image(self, geometry): spatial_references = { 3857: "+init=epsg:3857", # font: https://help.openstreetmap.org/questions/13250/what-is-the-correct-projection-i-should-use-with-mapnik 4326: "+init=epsg:4326", 4674: "+proj=longlat +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +no_defs ", 4618: "+proj=longlat +ellps=aust_SA +towgs84=-67.35,3.88,-38.22,0,0,0,0 +no_defs", 9999: "+proj=lcc +ellps=GRS80 +lat_0=49 +lon_0=-95 +lat+1=49 +lat_2=77 +datum=NAD83 +units=m +no_defs" } map = mapnik.Map(800, 600) ds = mapnik.CSV(inline='wkt\n"' + geometry.wkt + '"', filesize_max=500) layer = mapnik.Layer('world') map.background = mapnik.Color('white') # steelblue white geom_type = self.define_geometry_type(geometry) if geom_type not in ['polygon', 'multipolygon']: mapnik.load_map(map, 'style.xml') layer.srs = spatial_references[geometry.srs.srid] # object.wkt.srs layer.datasource = ds layer.styles.append(geom_type) map.layers.append(layer) map.zoom_all() image = mapnik.Image(800, 600) mapnik.render(map, image) image.save('geometry.png') with open('geometry.png', 'rb') as geometry_png: data = geometry_png.read() os.remove('geometry.png') return data style = mapnik.Style() rule = mapnik.Rule() polygon_symbolizer = mapnik.PolygonSymbolizer() polygon_symbolizer.fill = mapnik.Color('#33AA33') #('#f2eff9') rule.symbols.append(polygon_symbolizer) line_symbolizer = mapnik.LineSymbolizer() line_symbolizer.stroke = mapnik.Color('rgb(90%,90%,90%)') line_symbolizer.stroke_width = 0.1 rule.symbols.append(line_symbolizer) #point_symbolizer = mapnik.PointSymbolizer()#"marker-icon.png") #point_symbolizer.file = "marker-icon.png" #point_symbolizer.allow_overlap = True #rule.symbols.append(point_symbolizer) style.rules.append(rule) map.append_style('style', style) layer.srs = spatial_references[geometry.srs.srid] # object.wkt.srs layer.datasource = ds layer.styles.append('style') map.layers.append(layer) map.zoom_all() mapnik.render_to_file(map, 'geometry.png', 'png') with open('geometry.png', 'rb') as geometry_png: data = geometry_png.read() os.remove('geometry.png') return data