You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: VectorPython.Rmd
+57-64Lines changed: 57 additions & 64 deletions
Original file line number
Diff line number
Diff line change
@@ -42,7 +42,12 @@ OGR supports many different vector formats:
42
42
**OGR Data drivers:** A driver is an object that knows how to interact with a certain data type (e.g. a shapefile).
43
43
You need to know the right driver to read or write data. Some drivers might only be able to read content, but the majority can read and write.
44
44
45
-
```{r, engine='python'}
45
+
Start a terminal and see if you can load osgeo in Python.
46
+
```{r, engine='bash', eval = FALSE}
47
+
python
48
+
```
49
+
50
+
```{r, engine='python', eval = FALSE}
46
51
try:
47
52
from osgeo import ogr
48
53
except:
@@ -57,17 +62,42 @@ ogrinfo --formats
57
62
58
63
[More info about the different OGR formats](http://www.gdal.org/ogr_formats.html).
59
64
60
-
## Points
65
+
## Setting up environment
66
+
Before we continue with scripting, you need to setup your Python environment. In the previous Python lesson you learned about Conda and Jupyter Notebooks. We will use both again today. Check if you have made any conda environment named geoscripting.
67
+
68
+
```{r, eval=FALSE,engine='bash'}
69
+
## Display all your conda environments
70
+
conda info --envs
71
+
```
72
+
73
+
If you don't have a conda environment called 'geoscripting', create it first.
Open a new Ipython Notebook in an appropriate location. Output of the Python scripts from Jupyter Notebook will be saved in the repository where the .ipynb is stored.
61
90
62
-
What does "WKT" mean?
91
+
## Points
92
+
Now we continue with the tutorial. Try the script below and find out what "WKT" means.
63
93
64
94
```{r, engine='python'}
65
95
from osgeo import ogr
66
96
# Create a point geometry
67
97
wkt = "POINT (173914.00 441864.00)"
68
98
pt = ogr.CreateGeometryFromWkt(wkt)
69
99
print(pt)
70
-
# printhelp(osgeo.ogr)
100
+
# print(help(osgeo.ogr))
71
101
```
72
102
73
103
WKT (Well Known Text) is a sort of markup language that describes spatial information in a clean text format, there is an equivalent in binary format (easier for computers to process and more efficient for data transfer).
point = ogr.CreateGeometryFromWkt("POINT (5.6660 51.9872)")
137
+
point = ogr.CreateGeometryFromWkt("POINT (5.6660 51.9872)") #ogr uses lon, lat
108
138
point.Transform(transform)
109
-
printpoint.ExportToWkt()
139
+
print(point.ExportToWkt())
110
140
```
111
141
112
142
Are you still keeping track of your data and coordinate system?
@@ -133,16 +163,7 @@ Driver
133
163
Point
134
164
```
135
165
136
-
Start a new Python script within the `Python` console of QGIS (recommended for today!). Open QGIS Desktop, go to plugins and start python console (or use short ctrl + alt + p).
137
-
138
-
You can set the working directory using:
139
-
```{python, eval=FALSE}
140
-
import os
141
-
os.chdir('pathtoyourworkingdirectory')
142
-
print os.getcwd()
143
-
```
144
-
145
-
Now you can continue (you do not need to repeat the `import ` if you have already done so!):
166
+
Now we know how a file is made, you can continue to make a file:
146
167
147
168
* Set spatial reference
148
169
* Create shape file
@@ -153,18 +174,13 @@ Now you can continue (you do not need to repeat the `import ` if you have alread
153
174
* Flush
154
175
155
176
```{r, engine = 'python', eval=FALSE}
156
-
## Loading the modules
157
-
#from osgeo import ogr,osr
158
-
#import os
159
-
#os.chdir('./data')
160
-
161
177
## Is the ESRI Shapefile driver available?
162
178
driverName = "ESRI Shapefile"
163
-
drv = ogr.GetDriverByName(driverName)
179
+
drv = ogr.GetDriverByName(driverName)
164
180
if drv is None:
165
-
print"%s driver not available.\n" % driverName
181
+
print("%s driver not available.\n" % driverName)
166
182
else:
167
-
print"%s driver IS available.\n" % driverName
183
+
print("%s driver IS available.\n" % driverName)
168
184
```
169
185
170
186
After loading modules and setting the correct driver, we can create a new data source for a shapefile. Have a look that the layer does not exist in your data folder.
@@ -176,7 +192,7 @@ layername = "anewlayer"
176
192
177
193
## Create shape file
178
194
ds = drv.CreateDataSource(fn)
179
-
printds.GetRefCount()
195
+
print(ds.GetRefCount())
180
196
```
181
197
182
198
We created the datasource, but didn't make the file yet. Let's continue to add information to the shapefile. First add a coordinate reference system (CRS) or spatial reference.
@@ -239,8 +255,8 @@ Now that we created features with geometry, we can store the features in the lay
239
255
layer.CreateFeature(feature1)
240
256
layer.CreateFeature(feature2)
241
257
242
-
print"Extent of layer"
243
-
printlayer.GetExtent()
258
+
print("Extent of layer")
259
+
print(layer.GetExtent())
244
260
```
245
261
246
262
It has an extent now and it might seem we are finished now. We created geometry, features and a layer and assigned the `Esri Shapefile` driver to the layer. However the file still has to be saved. OGR doesn't have a Save() option. The shapefile is updated with the object structure when the script finished or when it is destroyed, if necessary SyncToDisk() maybe used.
@@ -254,42 +270,23 @@ Okay nice. You created a shapefile in Python from scratch. This is just a start.
254
270
255
271
```{r, engine = 'python', eval=FALSE}
256
272
## Export to other formats/representations:
257
-
print"KML file export"
258
-
printpoint2.ExportToKML()
273
+
print("KML file export")
274
+
print(point2.ExportToKML())
259
275
```
260
276
261
277
Spatial operations are possible to. Buffer around the point and export the buffer to a GML file.
262
278
263
279
```{r, engine = 'python', eval=FALSE}
264
280
## Buffering
265
281
buffer = point2.Buffer(1,1)
266
-
printbuffer.Intersects(point1)
282
+
print(buffer.Intersects(point1))
267
283
268
284
## More exports:
269
285
buffer.ExportToGML()
270
286
```
271
287
272
288
More spatial methods are available from the OGR module. If you are interested have a look at the methods section of this [tutorial](http://www2.geog.ucl.ac.uk/~plewis/geogg122/_build/html/Chapter4_GDAL/OGR_Python.html).
273
289
274
-
Let's open and visualize our files in QGIS. Files can even be opened from the `Python Console` in QGIS. Try the code below:
For our purposes, “ogr” will be used most of the time with vector data. Other popular drivers besides ogr are postgres (for PostgreSQL databases), KML, GML, Esri Shapefile or GeoJSON. [The python qgis cookbook](http://docs.qgis.org/testing/en/docs/pyqgis_developer_cookbook/loadlayer.html) gives more information on the use of the method and available drivers.
294
291
295
292
## Modify a shape file
@@ -302,21 +299,21 @@ ds = drv.Open(fn, 1)
302
299
303
300
## Check layers and get the first layer
304
301
layernr = ds.GetLayerCount()
305
-
printlayernr
302
+
print(layernr)
306
303
layer = ds.GetLayerByIndex(0)
307
-
printlayer
304
+
print(layer)
308
305
309
306
## Get number of features in shapefile layer
310
307
features_number = layer.GetFeatureCount()
311
-
print"number of features for this layer:", features_number
308
+
print("number of features for this layer:", features_number)
Webtutorial about folium: [web-mapping-with-python-and-folium](http://pythonhow.com/web-mapping-with-python-and-folium)
384
-
377
+
and [latest webmapping with folium](http://folium.readthedocs.io/en/latest/quickstart.html).
378
+
379
+
385
380
## Clean up
386
-
387
381
From the terminal you can remove the created "points.shp" and related files using:
388
-
389
382
```{r, engine='bash', eval=FALSE}
390
383
echo "in the terminal you can use the following bash commands to easily remove files"
391
384
echo "list all the files starting with points*"
@@ -407,13 +400,13 @@ rm -v points*
407
400
408
401
# Assignment
409
402
410
-
Create your own shapefile of two point locations (e.g. a location of the GAIA building in Wageningen) in RD_New, buffer one point and make a webmap in Python. Make a well structured IPython Notebook.
403
+
Create your own shapefile of two point locations (e.g. a location of the GAIA building in Wageningen) in RD_New, buffer two points and make a webmap in Python. Make a well structured IPython Notebook.
411
404
412
405
- Create two points with coordinates from [Google Maps](https://www.google.nl/maps/?hl=en) or use the two points from the [R vector tutorial](https://geoscripting-wur.github.io/IntroToVector/).
413
406
- Set the projection (Lat/Long, you should know now the EPSG) and reproject to the Dutch projection RD_New
414
-
- Create a buffer around the points of 100m
415
-
- Export the two point to shape file (that can be imported in QGIS)
416
-
- Make a webmap of your buffer with leaflet
407
+
- Create a buffer around the two points of 100m
408
+
- Export the two points to shape file (that can be imported in QGIS)
409
+
- Make a webmap of your buffer with leaflet (Hint: your buffer is a polygon)
417
410
418
411
Bonus: print the distance between the two points (Hint: `Distance()`)
0 commit comments