Challenge Solutions
Challenge A: Import your file
file_path = output_path
rice_layer = iface.addVectorLayer(file_path,
baseName= "Rice Crops",
providerKey="ogr")
if not rice_layer:
print("Layer failed to load!")
else:
print("Layer loaded successfully!")
Challenge B: Writing to a Shapefile
output_path_shp = 'path_to_output/rice_subset.shp'
error = QgsVectorFileWriter.writeAsVectorFormat(layer = rice_layer,
fileName = output_path_shp,
fileEncoding = "UTF-8",
destCRS = rice_layer.crs(),
driverName = "ESRI Shapefile",
output file format
onlySelected=True)
if error_shp[0] == QgsVectorFileWriter.NoError:
print("Success: Shapefile has been created.")
else:
print("Error: Failed to write Shapefile.")
Challenge C: Count observations by field size
file_path = '/mnt/bigdrive/Dropbox/Presentations/YouthMappers_Thailand_2024/Tanzania/tz_labels.geojson'
rice_layer = iface.addVectorLayer(file_path,
baseName= "Rice Crops",
providerKey="ogr")
iface.addVectorLayer
if not rice_layer:
print("Layer failed to load!")
else:
print("Layer loaded successfully!")
crop_counts = {}
for feature in rice_layer.getFeatures():
crop_type = feature['primary_crop']
if crop_type in crop_counts:
crop_counts[crop_type] += 1
else:
crop_counts[crop_type] = 1
for crop, count in crop_counts.items():
print(f"{crop}: {count}")
Challenge D: Calculate the total area of each crop type
layer_path = "/mnt/bigdrive/Dropbox/Presentations/YouthMappers_Thailand_2024/South_Africa/sa_labels.geojson"
sa_labels_layer = iface.addVectorLayer(layer_path, "SA Labels", "ogr")
area_by_crop = {}
for feature in sa_labels_layer.getFeatures():
crop_type = feature['crop_name']
area_sqm = feature.geometry().area()
area_acres = area_sqm * 0.000247105
if crop_type in area_by_crop:
area_by_crop[crop_type] += area_acres
else:
area_by_crop[crop_type] = area_acres
for crop, area in area_by_crop.items():
print(f"{crop}: {area:.2f} acres")