Geography Reference
In-Depth Information
# Add the fields we're interested in
-
field_name = ogr.FieldDefn("Name", ogr.OFTString)
15
field_name.SetWidth(24)
-
layer.CreateField(field_name)
-
field_region = ogr.FieldDefn("Region", ogr.OFTString)
-
field_region.SetWidth(24)
-
layer.CreateField(field_region)
20
layer.CreateField(ogr.FieldDefn("Latitude", ogr.OFTReal))
-
layer.CreateField(ogr.FieldDefn("Longitude", ogr.OFTReal))
-
layer.CreateField(ogr.FieldDefn("Elevation", ogr.OFTInteger))
-
The first step is to create the driver in line 2. Once we have the driver, we
can use it to create the data source. In OGR, a shapefile data source can
be a directory of shapefiles, or it can be just a single file. In our case, we
are creating just a single shapefile as the data source in line 5. In line
8, we create a SpatialReference object and then use the ImportFromEPSG ( )
method to set the spatial reference to WGS84 using EPSG code 4326.
From the data source, we can create the layer as shown in line 12. The
first argument is just the name of the shapefile without the extension.
The second argument to CreateLayer ( ) is the spatial reference. The final
argument is the feature type—in our case a wkbPoint .
With the layer created, we can add the field definitions in lines 15
through 23. For the text fields, Name and Region , we create the field
object, set an arbitrary width of 24, and then use the CreateField ( ) to
add it to our layer. For the numeric fields, we can create the field all in
one step as in line 21.
The layer is now ready for some data:
Download import_volcanoes.py
# Process the text file and add the attributes and features to the shapefile
Line 1
for row in reader:
-
# create the feature
-
feature = ogr.Feature(layer.GetLayerDefn())
-
# Set the attributes using the values from the delimited text file
5
feature.SetField("Name", row['Name'])
-
feature.SetField("Region", row['Region'])
-
feature.SetField("Latitude", row['Latitude'])
-
feature.SetField("Longitude", row['Longitude'])
-
feature.SetField("Elevation", row['Elev'])
10
-
-
# create the WKT for the feature using Python string formatting
wkt = "POINT(%f %f)" %
(float(row['Longitude']) , float(row['Latitude']))
-
-
15
# Create the point from the Well Known Txt
point = ogr.CreateGeometryFromWkt(wkt)
-
-
 
Search WWH ::




Custom Search