-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhw2b.py
85 lines (70 loc) · 2.3 KB
/
hw2b.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
#-------------------------------------------------------------------------------
# Name: Reproject a shapfile
# Purpose:
#
# Author: Hoa
#
# Created: 07/07/2014
# Copyright: (c) Hoa 2014
# Licence: <your licence>
#-------------------------------------------------------------------------------
import ogr, os, osr, sys
# Working directory
os.chdir(r'E:\GFD_DATA\Study\PYHTHON\Python with GDAL\Week 2 Creating geometries and handling projections\ospy_data2')
# driver shapfile
driver = ogr.GetDriverByName('ESRI shapefile')
# Create the input spatialreference EPGS 4269
inputCD = osr.SpatialReference()
inputCD.ImportFromEPSG(4269)
# Create the output spatial reference EPGS 26912
outputCD = osr.SpatialReference()
outputCD.ImportFromEPSG(26912)
# Create coordinate transform
coortrans = osr.CoordinateTransformation(inputCD, outputCD)
# Open input data and get the layer
inds = driver.Open('hwa2a.shp', 0)
if inds is None:
print 'Could not open file'
sys.exit(1)
inlayer = inds.GetLayer()
# Create a new data source and layer
shp = 'hw2b.shp'
if os.path.exists(shp):
driver.DeleteDataSource(shp)
outds = driver.CreateDataSource(shp)
if outds is None:
print 'Could not create file'
sys.exit(1)
outlayer = outds.CreateLayer('hw2b', geom_type = ogr.wkbPolygon)
# Get the fielddefn for the country name field
feature = inlayer.GetFeature(0)
fieldDefn = feature.GetFieldDefnRef('name')
# Add the field to the output shapefile
outlayer.CreateField(fieldDefn)
# Get the featureDefn for the output file
featureDefn = outlayer.GetLayerDefn()
# Loop through the input features
inFeature = inlayer.GetNextFeature()
while inFeature:
# Get input geometry
geom = inFeature.GetGeometryRef()
# Reproject the geometry
# Create a new feature
outFeature = ogr.Feature(featureDefn)
# Set the geometry and attribute
outFeature.SetGeometry(geom)
outFeature.SetField('name', inFeature.GetField('name'))
# Add the feature to the shp
outlayer.CreateFeature(outFeature)
# Destroy the features and get next input feature
outFeature.Destroy()
inFeature.Destroy()
inFeature = inlayer.GetNextFeature()
# Close the shp
inds.Destroy()
outds.Destroy()
# Create .prj file
outputCD.MorphFromESRI()
file = open('hw2b.prj', 'w')
file.write(outputCD.ExportToWkt())
file.close()