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 test_reading_json_from_string(): json = open('../data/json/points.geojson', 'r').read() if 'ogr' in mapnik.DatasourceCache.plugin_names(): ds = mapnik.Ogr(file=json, layer_by_index=0) features = ds.all_features() num_feats = len(features) eq_(num_feats, 5)
def compare_shape_between_mapnik_and_ogr(shapefile, query=None): plugins = mapnik.DatasourceCache.instance().plugin_names() if 'shape' in plugins and 'ogr' in plugins: ds1 = mapnik.Ogr(file=shapefile, layer_by_index=0) ds2 = mapnik.Shapefile(file=shapefile) if query: fs1 = ds1.features(query) fs2 = ds2.features(query) else: fs1 = ds1.featureset() fs2 = ds2.featureset() count = 0 while (True): count += 1 feat1 = fs1.next() feat2 = fs2.next() if not feat1: break #import pdb;pdb.set_trace() eq_( feat1.id(), feat2.id(), '%s : ogr feature id %s "%s" does not equal shapefile feature id %s "%s"' % (count, feat1.id(), str( feat1.attributes), feat2.id(), str(feat2.attributes))) return True
def test_ogr_reading_gpx_waypoint(): ds = mapnik.Ogr(file='../data/gpx/empty.gpx', layer='waypoints') e = ds.envelope() eq_(e.minx, -122) eq_(e.miny, 48) eq_(e.maxx, -122) eq_(e.maxy, 48)
def test_ogr_layer_by_sql(): if 'ogr' in mapnik.DatasourceCache.plugin_names(): ds = mapnik.Ogr(file='../data/shp/poly.shp', layer_by_sql='SELECT * FROM poly WHERE EAS_ID = 168') features = ds.all_features() num_feats = len(features) eq_(num_feats, 1)
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 test_reading_json_from_string(): json = open('../data/json/points.json', 'r').read() lyr = mapnik.Layer('test') if 'ogr' in mapnik.DatasourceCache.instance().plugin_names(): lyr.datasource = mapnik.Ogr(file=json, layer_by_index=0) features = lyr.datasource.all_features() num_feats = len(features) eq_(num_feats, 5)
def test_total_feature_count_json(): lyr = mapnik.Layer('test') if 'ogr' in mapnik.DatasourceCache.instance().plugin_names(): lyr.datasource = mapnik.Ogr(file='../data/json/points.json', layer_by_index=0) features = lyr.datasource.all_features() num_feats = len(features) eq_(num_feats, 5)
def test_shapefile_init(): s = mapnik.Ogr(file='../../demo/data/boundaries.shp', layer_by_index=0) e = s.envelope() assert_almost_equal(e.minx, -11121.6896651, places=7) assert_almost_equal(e.miny, -724724.216526, places=6) assert_almost_equal(e.maxx, 2463000.67866, places=5) assert_almost_equal(e.maxy, 1649661.267, places=3)
def test_ogr_layer_by_sql(): lyr = mapnik.Layer('test') if 'ogr' in mapnik.DatasourceCache.instance().plugin_names(): lyr.datasource = mapnik.Ogr( file='../data/shp/poly.shp', layer_by_sql='SELECT * FROM poly WHERE EAS_ID = 168') features = lyr.datasource.all_features() num_feats = len(features) eq_(num_feats, 1)
def ensure_geometries_are_interpreted_equivalently(filename): ds1 = mapnik.Ogr(file=filename, layer_by_index=0) ds2 = mapnik.Shapefile(file=filename) fs1 = ds1.featureset() fs2 = ds2.featureset() count = 0 for feat1, feat2 in zip(fs1, fs2): count += 1 eq_(feat1.attributes, feat2.attributes)
def test_ogr_extent_parameter(): ds = mapnik.Ogr(file='../data/shp/world_merc.shp', layer_by_index=0, extent='-1,-1,1,1') e = ds.envelope() eq_(e.minx, -1) eq_(e.miny, -1) eq_(e.maxx, 1) eq_(e.maxy, 1)
def test_shapefile_polygon_feature_query_id(): bbox = (15523428.2632, 4110477.6323, -11218494.8310, 7495720.7404) query = mapnik.Query(mapnik.Box2d(*bbox)) if 'ogr' in mapnik.DatasourceCache.instance().plugin_names(): ds = mapnik.Ogr(file='../data/shp/world_merc.shp', layer_by_index=0) for fld in ds.fields(): query.add_property_name(fld) compare_shape_between_mapnik_and_ogr('../data/shp/world_merc.shp', query)
def ensure_geometries_are_interpreted_equivalently(filename): ds1 = mapnik.Ogr(file=filename, layer_by_index=0) ds2 = mapnik.Shapefile(file=filename) fs1 = ds1.featureset() fs2 = ds2.featureset() count = 0 import itertools for feat1, feat2 in itertools.izip(fs1, fs2): count += 1 eq_(str(feat1), str(feat2))
def test_ogr_reading_gpx_waypoint(): ds = mapnik.Ogr(file='../data/gpx/empty.gpx',layer='waypoints') e = ds.envelope() eq_(e.minx,-122) eq_(e.miny,48) eq_(e.maxx,-122) eq_(e.maxy,48) meta = ds.describe() eq_(meta['geometry_type'],mapnik.DataGeometryType.Point) eq_('+proj=longlat' in meta['proj4'],True)
def test_ogr_extent_parameter(): ds = mapnik.Ogr(file='../data/shp/world_merc.shp',layer_by_index=0,extent='-1,-1,1,1') e = ds.envelope() eq_(e.minx,-1) eq_(e.miny,-1) eq_(e.maxx,1) eq_(e.maxy,1) meta = ds.describe() eq_(meta['geometry_type'],mapnik.DataGeometryType.Polygon) eq_('+proj=merc' in meta['proj4'],True)
def test_shapefile_init(): ds = mapnik.Ogr(file='../data/shp/boundaries.shp',layer_by_index=0) e = ds.envelope() assert_almost_equal(e.minx, -11121.6896651, places=7) assert_almost_equal(e.miny, -724724.216526, places=6) assert_almost_equal(e.maxx, 2463000.67866, places=5) assert_almost_equal(e.maxy, 1649661.267, places=3) meta = ds.describe() eq_(meta['geometry_type'],mapnik.DataGeometryType.Polygon) eq_('+proj=lcc' in meta['proj4'],True)
def test_total_feature_count_json(): if 'ogr' in mapnik.DatasourceCache.plugin_names(): ds = mapnik.Ogr(file='../data/json/points.geojson', layer_by_index=0) desc = ds.describe() eq_(desc['geometry_type'], mapnik.DataGeometryType.Point) eq_(desc['name'], 'ogr') eq_(desc['type'], mapnik.DataType.Vector) eq_(desc['encoding'], 'utf-8') features = ds.all_features() num_feats = len(features) eq_(num_feats, 5)
def test_shapefile_properties(): ds = mapnik.Ogr(file='../../demo/data/boundaries.shp',layer_by_index=0) f = ds.features_at_point(ds.envelope().center(), 0.001).features[0] eq_(ds.geometry_type(),mapnik.DataGeometryType.Polygon) eq_(f['CGNS_FID'], u'6f733341ba2011d892e2080020a0f4c9') eq_(f['COUNTRY'], u'CAN') eq_(f['F_CODE'], u'FA001') eq_(f['NAME_EN'], u'Quebec') eq_(f['Shape_Area'], 1512185733150.0) eq_(f['Shape_Leng'], 19218883.724300001)
def test_that_nonexistant_query_field_throws(**kwargs): ds = mapnik.Ogr(file='../data/shp/world_merc.shp',layer_by_index=0) eq_(len(ds.fields()),11) eq_(ds.fields(),['FIPS', 'ISO2', 'ISO3', 'UN', 'NAME', 'AREA', 'POP2005', 'REGION', 'SUBREGION', 'LON', 'LAT']) eq_(ds.field_types(),['str', 'str', 'str', 'int', 'str', 'int', 'int', 'int', 'int', 'float', 'float']) query = mapnik.Query(ds.envelope()) for fld in ds.fields(): query.add_property_name(fld) # also add an invalid one, triggering throw query.add_property_name('bogus') ds.features(query)
def test_ogr_empty_data_should_not_throw(): default_logging_severity = mapnik.logger.get_severity() mapnik.logger.set_severity(mapnik.severity_type.None) # use logger to silence expected warnings for layer in ['routes', 'tracks', 'route_points', 'track_points']: ds = mapnik.Ogr(file='../data/gpx/empty.gpx', layer=layer) e = ds.envelope() eq_(e.minx, 0) eq_(e.miny, 0) eq_(e.maxx, 0) eq_(e.maxy, 0) mapnik.logger.set_severity(default_logging_severity)
def ensure_geometries_are_interpreted_equivalently(filename): ds1 = mapnik.Ogr(file=filename,layer_by_index=0) ds2 = mapnik.Shapefile(file=filename) fs1 = ds1.featureset() fs2 = ds2.featureset() count = 0; while(True): count += 1 feat1 = fs1.next() feat2 = fs2.next() if not feat1: break eq_(str(feat1),str(feat2))
def test_ogr_empty_data_should_not_throw(): default_logging_severity = mapnik.logger.get_severity() mapnik.logger.set_severity(mapnik.severity_type.None) # use logger to silence expected warnings for layer in ['routes', 'tracks', 'route_points', 'track_points']: ds = mapnik.Ogr(file='../data/gpx/empty.gpx',layer=layer) e = ds.envelope() eq_(e.minx,0) eq_(e.miny,0) eq_(e.maxx,0) eq_(e.maxy,0) mapnik.logger.set_severity(default_logging_severity) meta = ds.describe() eq_(meta['geometry_type'],mapnik.DataGeometryType.Point) eq_('+proj=longlat' in meta['proj4'],True)
def test_shapefile_properties(): ds = mapnik.Ogr(file='../../demo/data/boundaries.shp', layer_by_index=0, encoding='latin1') f = ds.features_at_point(ds.envelope().center()).features[0] eq_(ds.geometry_type(), mapnik.DataGeometryType.Polygon) eq_(f['CGNS_FID'], u'6f733341ba2011d892e2080020a0f4c9') eq_(f['COUNTRY'], u'CAN') eq_(f['F_CODE'], u'FA001') eq_(f['NAME_EN'], u'Quebec') # this seems to break if icu data linking is not working eq_(f['NOM_FR'], u'Qu\xe9bec') eq_(f['NOM_FR'], u'Québec') eq_(f['Shape_Area'], 1512185733150.0) eq_(f['Shape_Leng'], 19218883.724300001)
def test_feature_hit_count(): raise Todo("need to optimize multigeom bbox handling in shapeindex") # results in different results between shp and ogr! #bbox = (-14284551.8434, 2074195.1992, -7474929.8687, 8140237.7628) bbox = (1113194.91, 4512803.085, 2226389.82, 6739192.905) query = mapnik.Query(mapnik.Box2d(*bbox)) if 'ogr' in mapnik.DatasourceCache.instance().plugin_names(): ds1 = mapnik.Ogr(file='../data/shp/world_merc.shp', layer_by_index=0) for fld in ds1.fields(): query.add_property_name(fld) ds2 = mapnik.Shapefile(file='../data/shp/world_merc.shp') count1 = len(ds1.features(query).features) count2 = len(ds2.features(query).features) eq_( count1, count2, "Feature count differs between OGR driver (%s features) and Shapefile Driver (%s features) when querying the same bbox" % (count1, count2))
def test_shapefile_properties(): # NOTE: encoding is latin1 but gdal >= 1.9 should now expose utf8 encoded features # See SHAPE_ENCODING for overriding: http://gdal.org/ogr/drv_shapefile.html # So: failure for the NOM_FR field is expected for older gdal ds = mapnik.Ogr(file='../../demo/data/boundaries.shp', layer_by_index=0) f = ds.features_at_point(ds.envelope().center()).features[0] eq_(ds.geometry_type(), mapnik.DataGeometryType.Polygon) eq_(f['CGNS_FID'], u'6f733341ba2011d892e2080020a0f4c9') eq_(f['COUNTRY'], u'CAN') eq_(f['F_CODE'], u'FA001') eq_(f['NAME_EN'], u'Quebec') # this seems to break if icu data linking is not working eq_(f['NOM_FR'], u'Qu\xe9bec') eq_(f['NOM_FR'], u'Québec') eq_(f['Shape_Area'], 1512185733150.0) eq_(f['Shape_Leng'], 19218883.724300001)
def ensure_geometries_are_interpreted_equivalently(filename): ds1 = mapnik.Ogr(file=filename, layer_by_index=0) ds2 = mapnik.Shapefile(file=filename) fs1 = ds1.featureset() fs2 = ds2.featureset() count = 0 while (True): count += 1 feat1 = fs1.next() feat2 = fs2.next() if not feat1: break eq_(str(feat1), str(feat2)) eq_(feat1.geometries().to_wkt(), feat2.geometries().to_wkt()) eq_(feat1.geometries().to_wkb(mapnik.wkbByteOrder.NDR), feat2.geometries().to_wkb(mapnik.wkbByteOrder.NDR)) eq_(feat1.geometries().to_wkb(mapnik.wkbByteOrder.XDR), feat2.geometries().to_wkb(mapnik.wkbByteOrder.XDR))
def test_shapefile_properties(): s = mapnik.Ogr(file='../../demo/data/boundaries.shp', layer_by_index=0, encoding='latin1') f = s.features_at_point(s.envelope().center()).features[0] eq_(f['CGNS_FID'], u'6f733341ba2011d892e2080020a0f4c9') eq_(f['COUNTRY'], u'CAN') eq_(f['F_CODE'], u'FA001') eq_(f['NAME_EN'], u'Quebec') # this seems to break if icu data linking is not working eq_(f['NOM_FR'], u'Qu\xe9bec') eq_(f['NOM_FR'], u'Québec') eq_(f['Shape_Area'], 1512185733150.0) eq_(f['Shape_Leng'], 19218883.724300001) # Check that the deprecated interface still works, # remove me once the deprecated code is cleaned up eq_(f.properties['Shape_Leng'], 19218883.724300001)