def write_vector_data(data, projection, geometry, filename, keywords=None): """Write point data and any associated attributes to vector file Input: data: List of N dictionaries each with M fields where M is the number of attributes. A value of None is acceptable. projection: WKT projection information geometry: List of points or polygons. filename: Output filename keywords: Optional dictionary Note: The only format implemented is GML and SHP so the extension must be either .gml or .shp # FIXME (Ole): When the GML driver is used, # the spatial reference is not stored. # I suspect this is a bug in OGR. Background: * http://www.gdal.org/ogr/ogr_apitut.html (last example) * http://invisibleroads.com/tutorials/gdal-shapefile-points-save.html """ V = Vector(data, projection, geometry, keywords=keywords) V.write_to_file(filename)
def csv2shp(path, lonname='Bujur', latname='Lintang'): # Read csv data reader = csv.DictReader(open(path, 'r')) data = [] for x in reader: data.append(x) # Determine latitude and longitude fields fieldnames = reader.fieldnames msg = ('Could not find requested longitude "%s" in %s. Available ' 'field names are: %s' % (lonname, path, str(fieldnames))) assert lonname in fieldnames, msg msg = ('Could not find requested latitude "%s" in %s. Available ' 'field names are: %s' % (latname, path, str(fieldnames))) assert latname in fieldnames, msg # Extract point geometry lon = [float(x[lonname]) for x in data] lat = [float(x[latname]) for x in data] geometry = zip(lon, lat) # Replace spaces in attribute names with underscores (issue #177) for i, D in enumerate(data): D_clean = {} for key in D: D_clean[key.replace(' ', '_')] = D[key] data[i] = D_clean # Create vector object V = Vector(data=data, projection=DEFAULT_PROJECTION, geometry=geometry) # Write as shapefile basename, _ = os.path.splitext(path) V.write_to_file(basename + '.shp') fid = open(basename + '.keywords', 'w') fid.write('category:exposure\n') fid.write('subcategory:building\n') fid.write('datatype:sigab\n') fid.close()
def test_vector_class(self): """Consistency of vector class for point data """ # Read data file layername = 'lembang_schools.shp' filename = '%s/%s' % (TESTDATA, layername) V = read_layer(filename) # Make a smaller dataset V_ref = V.get_topN('FLOOR_AREA', 5) geometry = V_ref.get_geometry() data = V_ref.get_data() projection = V_ref.get_projection() # Create new object from test data V_new = Vector(data=data, projection=projection, geometry=geometry) # Check assert V_new == V_ref assert not V_new != V_ref # Write this new object, read it again and check tmp_filename = unique_filename(suffix='.shp') V_new.write_to_file(tmp_filename) V_tmp = read_layer(tmp_filename) assert V_tmp == V_ref assert not V_tmp != V_ref # Check that equality raises exception when type is wrong try: V_tmp == Raster() except TypeError: pass else: msg = 'Should have raised TypeError' raise Exception(msg)