├── .gitattributes
├── .gitignore
├── Chapter01
├── B06246_01_01_syspath.py
├── B06246_01_02_console.py
├── B06246_01_03_start_python.py
├── B06246_01_04_scriptrun.py
├── B06246_01_05_ui_myplugin.ui
├── B06246_01_06_MapImage.py
├── B06246_01_07_plugins.xml
├── B06246_01_08_myMap.py
├── B06246_01_09_globalset.py
├── B06246_01_10_projectset.py
└── B06246_01_11_path.py
├── Chapter02
├── B06246_02_01-loadFile.py
├── B06246_02_02-loadGeoDB.py
├── B06246_02_03-seeFeatures.py
├── B06246_02_04-seeAttributes.py
├── B06246_02_05-filterGeom.py
├── B06246_02_06-filterAttributes.py
├── B06246_02_07-buffer.py
├── B06246_02_08-measurePts.py
├── B06246_02_09-measureLn.py
├── B06246_02_10-measureArea.py
├── B06246_02_11-Index.py
├── B06246_02_12-Bearing.py
├── B06246_02_13-CSV.py
└── B06246_02_14-metadata.py
├── Chapter03
├── B06246_03_01-memory.py
├── B06246_03_02-add-pt.py
├── B06246_03_03-add-ln.py
├── B06246_03_04-add-poly.py
├── B06246_03_05-add-attr.py
├── B06246_03_06-add-fld.py
├── B06246_03_07-join.py
├── B06246_03_08-move.py
├── B06246_03_09-chg.py
├── B06246_03_10-del.py
├── B06246_03_11-del.py
├── B06246_03_12-reproj.py
├── B06246_03_13-kml-gjson.py
├── B06246_03_14-merge.py
├── B06246_03_15-split.py
├── B06246_03_16-gen.py
├── B06246_03_17-diss.py
├── B06246_03_18-union.py
├── B06246_03_19-raster.py
└── B06246_03_19a-gpkg.py
├── Chapter04
├── B06246_04_01-LoadRaster.py
├── B06246_04_02-NetCDF.py
├── B06246_04_03-CellSize.py
├── B06246_04_04-WidthHeight.py
├── B06246_04_05-CountingBands.py
├── B06246_04_06-SwapBands.py
├── B06246_04_07-QueryPoint.py
├── B06246_04_08-Reproject.py
├── B06246_04_09-Hillshade.py
├── B06246_04_10-Contours.py
├── B06246_04_11-GridSample.py
├── B06246_04_12-PointDEM.py
├── B06246_04_13-CommExt.py
├── B06246_04_14-Resample.py
├── B06246_04_15-CountValues.py
├── B06246_04_16-Mosaic.py
├── B06246_04_17-TIFF2JPG.py
├── B06246_04_18-Pyramids.py
├── B06246_04_19-Pixel2World.py
├── B06246_04_20-World2Pixel.py
├── B06246_04_21-KML.py
├── B06246_04_22-Classify.py
├── B06246_04_23-Raster2Vec.py
├── B06246_04_24-GCP.py
└── B06246_04_25-Clip.py
├── Chapter05
├── B06246_05_01-canvas.py
├── B06246_05_02-units.py
├── B06246_05_03-iter.py
├── B06246_05_04-symbol.py
├── B06246_05_05-transparentfill.py
├── B06246_05_06-filled_marker.py
├── B06246_05_07-ramp.py
├── B06246_05_08-csvcolor.py
├── B06246_05_09-complex.py
├── B06246_05_10-icons.py
├── B06246_05_11-outline.py
├── B06246_05_12-arrow.py
├── B06246_05_13-graduated.py
├── B06246_05_14-categorize.py
├── B06246_05_15-live.py
├── B06246_05_16-shapeburst.py
├── B06246_05_17-bookmark.py
├── B06246_05_18-navigate.py
├── B06246_05_19-vis.py
├── B06246_05_20-svg.py
├── B06246_05_21-pie.py
├── B06246_05_22-25D.py
├── B06246_05_23-xyz.py
├── B06246_05_24-esri.py
├── B06246_05_25-label.py
├── B06246_05_26-nullsym.py
├── B06246_05_27-transparency.py
├── B06246_05_28-add.py
├── B06246_05_29-point.py
├── B06246_05_30-poly.py
├── B06246_05_31-select.py
└── B06246_05_32-coord.py
├── Chapter06
├── B06246_06_01-renderer.py
├── B06246_06_02-composer.py
├── B06246_06_03-labels.py
├── B06246_06_04-scalebar.py
├── B06246_06_05-arrow.py
├── B06246_06_06-logo.py
├── B06246_06_07-vlegend.py
├── B06246_06_07a-hlegend.py
├── B06246_06_08-shape.py
├── B06246_06_09-grid.py
├── B06246_06_10-table.py
├── B06246_06_11-world_file.py
├── B06246_06_12-save_project.py
├── B06246_06_13-load_project.py
└── MapComposer.py
├── Chapter07
├── 4985_07_01-logs.py
├── 4985_07_02-msg.py
├── 4985_07_03-warn.py
├── 4985_07_04-error.py
├── 4985_07_05-progress.py
├── 4985_07_06-text.py
├── 4985_07_07-file.py
├── 4985_07_08-combo.py
├── 4985_07_09-radio.py
├── 4985_07_10-checkboxes.py
├── 4985_07_11-dockwidget.py
├── 4985_07_12-statusbar.py
├── 4985_07_13-messagebar.py
├── 4985_07_14-messagebarwidget.py
├── 4985_07_15-tabs.py
├── 4985_07_16-wizard.py
└── 4985_07_17-ontop.py
├── Chapter08
├── B06246_08_01-ndvi.py
├── B06246_08_02-geocode.py
├── B06246_08_03-raster.py
├── B06246_08_04-network.py
├── B06246_08_05-routing.py
├── B06246_08_06-tracking.py
├── B06246_08_07-mapbook.py
├── B06246_08_08-lcp.py
├── B06246_08_09-nn.py
├── B06246_08_10-lidar.py
├── B06246_08_11-heatmap.py
├── B06246_08_12-dotdensity.py
├── B06246_08_13-fielddata.py
├── B06246_08_14-slope.py
├── B06246_08_15-geolocate.py
├── B06246_08_16-change.py
├── B06246_08_17-irregular.py
└── B06246_08_18-multitemporal.py
├── Chapter09
├── B06246_09_01-tiles.py
├── B06246_09_02-cloud.py
├── B06246_09_03-rules.py
├── B06246_09_04-layerdef.py
├── B06246_09_05-null.py
├── B06246_09_06-genquery.py
├── B06246_09_07-alpha.py
├── B06246_09_08-geoio.py
├── B06246_09_09-output.py
├── B06246_09_10-points.py
├── B06246_09_11-exprlbl.py
├── B06246_09_12-forms.py
├── B06246_09_13-lines.py
├── B06246_09_14-diffcrs.py
├── B06246_09_15-htmlbls.py
├── B06246_09_16-osmpoi.py
├── B06246_09_17-proxy.py
├── B06246_09_18-sched.py
├── B06246_09_19-3D.py
├── B06246_09_20-globe.py
├── B06246_09_21-globe_proj.py
└── B06246_09_22-animate.py
├── LICENSE
└── README.md
/.gitattributes:
--------------------------------------------------------------------------------
1 | # Auto detect text files and perform LF normalization
2 | * text=auto
3 |
4 | # Custom for Visual Studio
5 | *.cs diff=csharp
6 |
7 | # Standard to msysgit
8 | *.doc diff=astextplain
9 | *.DOC diff=astextplain
10 | *.docx diff=astextplain
11 | *.DOCX diff=astextplain
12 | *.dot diff=astextplain
13 | *.DOT diff=astextplain
14 | *.pdf diff=astextplain
15 | *.PDF diff=astextplain
16 | *.rtf diff=astextplain
17 | *.RTF diff=astextplain
18 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Windows image file caches
2 | Thumbs.db
3 | ehthumbs.db
4 |
5 | # Folder config file
6 | Desktop.ini
7 |
8 | # Recycle Bin used on file shares
9 | $RECYCLE.BIN/
10 |
11 | # Windows Installer files
12 | *.cab
13 | *.msi
14 | *.msm
15 | *.msp
16 |
17 | # Windows shortcuts
18 | *.lnk
19 |
20 | # =========================
21 | # Operating System Files
22 | # =========================
23 |
24 | # OSX
25 | # =========================
26 |
27 | .DS_Store
28 | .AppleDouble
29 | .LSOverride
30 |
31 | # Thumbnails
32 | ._*
33 |
34 | # Files that might appear in the root of a volume
35 | .DocumentRevisions-V100
36 | .fseventsd
37 | .Spotlight-V100
38 | .TemporaryItems
39 | .Trashes
40 | .VolumeIcon.icns
41 |
42 | # Directories potentially created on remote AFP share
43 | .AppleDB
44 | .AppleDesktop
45 | Network Trash Folder
46 | Temporary Items
47 | .apdisk
48 |
--------------------------------------------------------------------------------
/Chapter01/B06246_01_01_syspath.py:
--------------------------------------------------------------------------------
1 | # Run in the PyQGIS console
2 | import sys
3 | sys.path
4 |
--------------------------------------------------------------------------------
/Chapter01/B06246_01_02_console.py:
--------------------------------------------------------------------------------
1 | # Run from the QGIS Python console
2 |
3 | layer = QgsVectorLayer('Point?crs=epsg:4326', 'MyPoint' , "memory")
4 | pr = layer.dataProvider()
5 | pt = QgsFeature()
6 | point1 = QgsPoint(20,20)
7 | pt.setGeometry(QgsGeometry.fromPoint(point1))
8 | pr.addFeatures([pt])
9 | layer.updateExtents()
10 | QgsMapLayerRegistry.instance().addMapLayers([layer])
11 |
--------------------------------------------------------------------------------
/Chapter01/B06246_01_03_start_python.py:
--------------------------------------------------------------------------------
1 | # Place in /.qgis2
2 | from console import console
3 | console.console_show()
--------------------------------------------------------------------------------
/Chapter01/B06246_01_04_scriptrun.py:
--------------------------------------------------------------------------------
1 | from PyQt4.QtCore import *
2 | from PyQt4.QtGui import *
3 | from qgis.core import *
4 | from qgis.gui import *
5 |
6 | def run_script(iface):
7 | """ Put your code here and remove the pass statement"""
8 | layer = QgsVectorLayer('Polygon?crs=epsg:4326', 'Mississippi' , "memory")
9 | pr = layer.dataProvider()
10 | poly = QgsFeature()
11 | geom = QgsGeometry.fromWkt("""POLYGON ((-88.82 34.99,
12 | -88.09 34.89,
13 | -88.39 30.34,
14 | -89.57 30.18,
15 | -89.73 31,
16 | -91.63 30.99,
17 | -90.87 32.37,
18 | -91.23 33.44,
19 | -90.93 34.23,
20 | -90.30 34.99,
21 | -88.82 34.99))""")
22 | poly.setGeometry(geom)
23 | pr.addFeatures([poly])
24 | layer.updateExtents()
25 | QgsMapLayerRegistry.instance().addMapLayers([layer])
26 |
--------------------------------------------------------------------------------
/Chapter01/B06246_01_05_ui_myplugin.ui:
--------------------------------------------------------------------------------
1 |
2 |
3 | MyPlugin
4 |
5 |
6 |
7 | 0
8 | 0
9 | 400
10 | 300
11 |
12 |
13 |
14 | MyPlugin
15 |
16 |
17 |
18 |
19 | 30
20 | 240
21 | 341
22 | 32
23 |
24 |
25 |
26 | Qt::Horizontal
27 |
28 |
29 | QDialogButtonBox::Cancel|QDialogButtonBox::Ok
30 |
31 |
32 |
33 |
34 |
35 | 120
36 | 80
37 | 201
38 | 20
39 |
40 |
41 |
42 |
43 | 14
44 |
45 |
46 |
47 | Geospatial Python Rocks!
48 |
49 |
50 |
51 |
52 |
53 |
54 | buttonBox
55 | accepted()
56 | MyPlugin
57 | accept()
58 |
59 |
60 | 248
61 | 254
62 |
63 |
64 | 157
65 | 274
66 |
67 |
68 |
69 |
70 | buttonBox
71 | rejected()
72 | MyPlugin
73 | reject()
74 |
75 |
76 | 316
77 | 260
78 |
79 |
80 | 286
81 | 274
82 |
83 |
84 |
85 |
86 |
87 |
--------------------------------------------------------------------------------
/Chapter01/B06246_01_06_MapImage.py:
--------------------------------------------------------------------------------
1 | from qgis.utils import iface
2 | import datetime
3 | c = iface.mapCanvas()
4 | t = '{:%Y%m%d%H%M%S}'.format(datetime.datetime.now())
5 | img_path = "
\n”)[1].split(“<”)[0].split(“,”)
7 | lyr_cap = [x.strip() for x in lyr_cap]
8 | # [u'Add Features', u'Delete Features', u'Change Attribute Values',
9 | # u'Add Attributes', u'Delete Attributes', u'Rename Attributes',
10 | # u'Create Spatial Index', u'Create Attribute Indexes',
11 | # u'Fast Access to Features at ID', u'Change Geometries']
12 |
13 |
--------------------------------------------------------------------------------
/Chapter03/B06246_03_01-memory.py:
--------------------------------------------------------------------------------
1 | # Creating a Vector Layer in Memory
2 |
3 | vectorLyr = QgsVectorLayer('Point?crs=epsg:4326&field=city:string(25)&field=population:int', 'Layer 1' , "memory")
4 | vectorLyr.isValid()
5 | # True
--------------------------------------------------------------------------------
/Chapter03/B06246_03_02-add-pt.py:
--------------------------------------------------------------------------------
1 | # Adding a Point Feature to a Vector Layer
2 |
3 | # https://github.com/GeospatialPython/Learn/raw/master/NYC_MUSEUMS_GEO.zip
4 |
5 | vectorLyr = QgsVectorLayer('/qgis_data/nyc/NYC_MUSEUMS_GEO.shp', 'Museums' , "ogr")
6 |
7 | vpr = vectorLyr.dataProvider()
8 |
9 | pnt = QgsGeometry.fromPoint(QgsPoint(-74.80,40.549))
10 |
11 | f = QgsFeature()
12 | f.setGeometry(pnt)
13 | vpr.addFeatures([f])
14 | vectorLyr.updateExtents()
15 |
16 |
--------------------------------------------------------------------------------
/Chapter03/B06246_03_03-add-ln.py:
--------------------------------------------------------------------------------
1 | # Adding a Line Feature to a Vector Layer
2 |
3 | # https://github.com/GeospatialPython/Learn/raw/master/paths.zip
4 |
5 | vectorLyr = QgsVectorLayer('/qgis_data/paths/paths.shp', 'Paths' , "ogr")
6 | vectorLyr.isValid()
7 | vpr = vectorLyr.dataProvider()
8 |
9 | points = []
10 | points.append(QgsPoint(430841.61703,5589485.34838))
11 | points.append(QgsPoint(432438.36523,5575114.61462))
12 | points.append(QgsPoint(447252.64015,5567663.12304))
13 |
14 | line = QgsGeometry.fromPolyline(points)
15 |
16 | f = QgsFeature()
17 | f.setGeometry(line)
18 | vpr.addFeatures([f])
19 | vectorLyr.updateExtents()
20 |
21 |
--------------------------------------------------------------------------------
/Chapter03/B06246_03_04-add-poly.py:
--------------------------------------------------------------------------------
1 | # Adding a Polygon Feature to a Vector Layer
2 |
3 | # https://github.com/GeospatialPython/Learn/raw/master/polygon.zip
4 |
5 | vectorLyr = QgsVectorLayer('/qgis_data/polygon/polygon.shp', 'Polygon' , "ogr")
6 | vectorLyr.isValid()
7 | vpr = vectorLyr.dataProvider()
8 |
9 | points = []
10 | points.append(QgsPoint(-123.26072,49.06822))
11 | points.append(QgsPoint(-127.19157,43.07367))
12 | points.append(QgsPoint(-120.70567,35.21197))
13 | points.append(QgsPoint(-115.89037,40.02726))
14 | points.append(QgsPoint(-113.04051,48.47859))
15 | points.append(QgsPoint(-123.26072,49.06822))
16 |
17 | poly = QgsGeometry.fromPolygon([points])
18 |
19 | f = QgsFeature()
20 | f.setGeometry(poly)
21 | vpr.addFeatures([f])
22 | vectorLyr.updateExtents()
23 |
--------------------------------------------------------------------------------
/Chapter03/B06246_03_05-add-attr.py:
--------------------------------------------------------------------------------
1 | # Adding a set of Attributes to a Vectory Layer
2 |
3 | # https://github.com/GeospatialPython/Learn/raw/master/NYC_MUSEUMS_GEO.zip
4 |
5 | vectorLyr = QgsVectorLayer('/qgis_data/nyc/NYC_MUSEUMS_GEO.shp', 'Museums' , "ogr")
6 | vectorLyr.isValid()
7 | vpr = vectorLyr.dataProvider()
8 |
9 | pnt = QgsGeometry.fromPoint(QgsPoint(-74.13401,40.62148))
10 |
11 | fields = vpr.fields()
12 |
13 | f = QgsFeature(fields)
14 | f.setGeometry(pnt)
15 |
16 | f.setAttribute(0,"Python Museum")
17 |
18 | vpr.addFeatures([f])
19 | vectorLyr.updateExtents()
20 |
21 |
--------------------------------------------------------------------------------
/Chapter03/B06246_03_06-add-fld.py:
--------------------------------------------------------------------------------
1 | # Adding a Field to a Vector Layer
2 |
3 | # https://github.com/GeospatialPython/Learn/raw/master/NYC_MUSEUMS_GEO.zip
4 |
5 | from PyQt4.QtCore import QVariant
6 |
7 | vectorLyr = QgsVectorLayer('/qgis_data/nyc/NYC_MUSEUMS_GEO.shp', 'Museums' , "ogr")
8 | vectorLyr.isValid()
9 | vpr = vectorLyr.dataProvider()
10 | vpr.addAttributes([QgsField("Admission", QVariant.Double)])
11 | vectorLyr.updateFields()
--------------------------------------------------------------------------------
/Chapter03/B06246_03_07-join.py:
--------------------------------------------------------------------------------
1 | # Join a Shapefile Attribute Table to a CSV File
2 |
3 | # https://github.com/GeospatialPython/Learn/raw/master/census.zip
4 | # See also: https://github.com/rldhont/Quantum-GIS/blob/master/python/plugins/processing/algs/qgis/JoinAttributes.py
5 |
6 | vectorLyr = QgsVectorLayer("/qgis_data/census/hancock_tracts.shp", "Hancock", "ogr")
7 | vectorLyr.isValid()
8 | infoLyr = QgsVectorLayer("/qgis_data/census/ACS_12_5YR_S1901_with_ann.csv", "Census", "ogr")
9 | infoLyr.isValid()
10 | QgsMapLayerRegistry.instance().addMapLayers([vectorLyr,infoLyr], False)
11 | info = QgsVectorJoinInfo()
12 | info.joinLayerId = infoLyr.id()
13 | info.joinFieldName = "GEOid2"
14 | info.targetFieldName = "GEOID"
15 | info.memoryCache = True
16 | vectorLyr.addJoin(info)
17 | QgsVectorFileWriter.writeAsVectorFormat(vectorLyr, "/qgis_data/census/joined.shp", "CP120", None, "ESRI Shapefile")
18 | joinedLyr = QgsVectorLayer("/qgis_data/census/joined.shp", "Joined", "ogr")
19 | vectorLyr.dataProvider().fields().count()
20 | # 12
21 | joinedLyr.dataProvider().fields().count()
22 | # 142
--------------------------------------------------------------------------------
/Chapter03/B06246_03_08-move.py:
--------------------------------------------------------------------------------
1 | # Moving Vector Layer Geometry
2 |
3 | # https://github.com/GeospatialPython/Learn/raw/master/NYC_MUSEUMS_GEO.zip
4 |
5 | vectorLyr = QgsVectorLayer('/qgis_data/nyc/NYC_MUSEUMS_GEO.shp', 'Museums' , "ogr")
6 | vectorLyr.isValid()
7 | feat_id = 22
8 | geom = QgsGeometry.fromPoint(QgsPoint(-74.20378,40.89642))
9 | vectorLyr.dataProvider().changeGeometryValues({feat_id : geom})
--------------------------------------------------------------------------------
/Chapter03/B06246_03_09-chg.py:
--------------------------------------------------------------------------------
1 | # Changing a Vector Layer Attribute
2 |
3 | # https://github.com/GeospatialPython/Learn/raw/master/NYC_MUSEUMS_GEO.zip
4 |
5 | vectorLyr = QgsVectorLayer('/qgis_data/nyc/NYC_MUSEUMS_GEO.shp', 'Museums' , "ogr")
6 | vectorLyr.isValid()
7 | feat_id = 22
8 | attr = {1:"(555) 555-5555"}
9 | vectorLyr.dataProvider().changeAttributeValues({feat_id : attr})
10 |
--------------------------------------------------------------------------------
/Chapter03/B06246_03_10-del.py:
--------------------------------------------------------------------------------
1 | # Deleting Vector Layer Feature (geometry and attributes)
2 |
3 | # https://github.com/GeospatialPython/Learn/raw/master/NYC_MUSEUMS_GEO.zip
4 |
5 | vectorLyr = QgsVectorLayer('/qgis_data/nyc/NYC_MUSEUMS_GEO.shp', 'Museums' , "ogr")
6 | vectorLyr.isValid()
7 | vectorLyr.dataProvider().deleteFeatures([ 22, 95 ])
8 |
--------------------------------------------------------------------------------
/Chapter03/B06246_03_11-del.py:
--------------------------------------------------------------------------------
1 | # Deleting a Vector Layer Field
2 |
3 | # https://github.com/GeospatialPython/Learn/raw/master/NYC_MUSEUMS_GEO.zip
4 |
5 | vectorLyr = QgsVectorLayer('/qgis_data/nyc/NYC_MUSEUMS_GEO.shp', 'Museums' , "ogr")
6 | vectorLyr.isValid()
7 | vectorLyr.dataProvider().deleteAttributes([1])
8 | vectorLyr.updateFields()
--------------------------------------------------------------------------------
/Chapter03/B06246_03_12-reproj.py:
--------------------------------------------------------------------------------
1 | # Reprojecting a Vector Layer
2 |
3 | # https://github.com/GeospatialPython/Learn/raw/master/MSCities_MSTM.zip
4 |
5 | import processing
6 | processing.runalg("qgis:reprojectlayer", "/qgis_data/ms/MSCities_MSTM.shp", "epsg:4326", "/qgis_data/ms/MSCities_MSTM_4326.shp")
--------------------------------------------------------------------------------
/Chapter03/B06246_03_13-kml-gjson.py:
--------------------------------------------------------------------------------
1 | # Converting a Shapefile to KML
2 |
3 | # https://github.com/GeospatialPython/Learn/raw/master/hancock.zip
4 |
5 | vectorLyr = QgsVectorLayer('/qgis_data/hancock/hancock.shp', 'Hancock' , "ogr")
6 | vectorLyr.isValid()
7 | dest_crs = QgsCoordinateReferenceSystem(4326)
8 | QgsVectorFileWriter.writeAsVectorFormat(vectorLyr, "/qgis_data/hancock/hancock.kml", "utf-8", dest_crs, "KML")
9 |
10 | # Or we can write out GeoJSON
11 | QgsVectorFileWriter.writeAsVectorFormat(vectorLyr, "/qgis_data/hancock/hancock.geojson", "utf-8", dest_crs, "GeoJSON")
--------------------------------------------------------------------------------
/Chapter03/B06246_03_14-merge.py:
--------------------------------------------------------------------------------
1 | # Merging Shapefiles
2 |
3 | # https://github.com/GeospatialPython/Learn/raw/master/tiled_footprints.zip
4 |
5 | # See also: processing.alghelp("qgis:mergevectorlayers")
6 |
7 | import glob
8 | import processing
9 |
10 | pth = "/qgis_data/tiled_footprints/"
11 | files = glob.glob(pth + "*.shp")
12 | out = pth + "merged.shp"
13 | processing.runandload("saga:mergelayers",";".join(files),"True", "True", out)
14 |
15 |
--------------------------------------------------------------------------------
/Chapter03/B06246_03_15-split.py:
--------------------------------------------------------------------------------
1 | # Splitting a Shapefile
2 |
3 | # https://github.com/GeospatialPython/Learn/raw/master/GIS_CensusTract.zip
4 |
5 | import processing
6 | pth = "/qgis_data/census/"
7 | processing.runalg("qgis:splitvectorlayer",pth + "GIS_CensusTract_poly.shp","COUNTY_8",pth)
8 |
--------------------------------------------------------------------------------
/Chapter03/B06246_03_16-gen.py:
--------------------------------------------------------------------------------
1 | # Generalizing a Vector Layer
2 |
3 | # https://github.com/GeospatialPython/Learn/raw/master/Mississippi.zip
4 |
5 | import processing
6 | processing.runandload("qgis:simplifygeometries","/qgis_data/ms/mississippi.shp",0.3,"/qgis_data/ms/generalize.shp")
--------------------------------------------------------------------------------
/Chapter03/B06246_03_17-diss.py:
--------------------------------------------------------------------------------
1 | # Dissolving Vector Shapes
2 |
3 | # https://github.com/GeospatialPython/Learn/raw/master/GIS_CensusTract.zip
4 |
5 | import processing
6 |
7 | processing.runandload("qgis:dissolve","/qgis_data/census/GIS_CensusTract_poly.shp",False,"COUNTY_8","/qgis_data/census/dissovle.shp")
--------------------------------------------------------------------------------
/Chapter03/B06246_03_18-union.py:
--------------------------------------------------------------------------------
1 | # Performing a Union on Vector Shapes
2 |
3 | # https://github.com/GeospatialPython/Learn/raw/master/union.zip
4 |
5 | import processing
6 | processing.runandload("qgis:union","/qgis_data/union/building.shp","/qgis_data/union/walkway.shp","/qgis_data/union/union.shp")
7 |
--------------------------------------------------------------------------------
/Chapter03/B06246_03_19-raster.py:
--------------------------------------------------------------------------------
1 | # Rasterizing a Vector Layer
2 |
3 | # https://github.com/GeospatialPython/Learn/raw/master/contour.zip
4 |
5 | import processing
6 |
7 | processing.runalg("gdalogr:rasterize","/qgis_data/rasters/contour.shp","ELEV",1,100,100,"428212.21,465052.21,5566050.73,5595210.73",False,5,"",4,75,6,1,False,0,"","/.qgis2/processing/outputs/raster_contour.tif")
--------------------------------------------------------------------------------
/Chapter03/B06246_03_19a-gpkg.py:
--------------------------------------------------------------------------------
1 | # Exporting a geopackage
2 |
3 | # https://github.com/GeospatialPython/Learn/raw/master/rivers.zip
4 |
5 | import os
6 | from osgeo import ogr
7 |
8 | # Path to the shapefiles
9 | pth = "/qgis_data/rivers/"
10 |
11 | # Create the base geopackage
12 | gpkg = os.path.join(pth + "rivers.gpkg")
13 | ds = ogr.GetDriverByName("GPKG").CreateDataSource(gpkg)
14 |
15 | # Add the first shapefile
16 | sf1 = ogr.Open(pth + "rivers.shp")
17 | sf_lyr1 = sf1.GetLayerByIndex(0)
18 | ds.CopyLayer(sf_lyr1, "rivers", [])
19 |
20 | # Close the dataset
21 | ds = None
22 |
23 | # Reopen the dataset in update mode
24 | ds = ogr.Open(gpkg, True)
25 |
26 | # Add the second shapefile
27 | sf2 = ogr.Open(pth + "junctions.shp")
28 | sf_lyr2 = sf2.GetLayerByIndex(0)
29 | ds.CopyLayer(sf_lyr2, "junctions", [])
30 |
31 | # Close the dataset
32 | ds = None
33 |
34 |
35 |
36 |
--------------------------------------------------------------------------------
/Chapter04/B06246_04_01-LoadRaster.py:
--------------------------------------------------------------------------------
1 | # Loading a Raster Layer
2 |
3 | # https://github.com/GeospatialPython/Learn/raw/master/SatImage.zip
4 |
5 | rasterLyr = QgsRasterLayer("/qgis_data/rasters/satimage.tif", "satimage")
6 | rasterLyr.isValid()
7 | # True
8 | QgsMapLayerRegistry.instance().addMapLayers([rasterLyr])
--------------------------------------------------------------------------------
/Chapter04/B06246_04_02-NetCDF.py:
--------------------------------------------------------------------------------
1 | # Load a NetCDF file
2 |
3 | # https://github.com/GeospatialPython/Learn/raw/master/tos_O1_2001-2002.nc
4 |
5 | uri='NETCDF:"/qgis_data/rasters/tos_O1_2001-2002.nc":tos'
6 | rlayer = QgsRasterLayer(uri,'Sea Surface Temperature')
7 | rlayer.isValid()
8 | QgsMapLayerRegistry.instance().addMapLayer(rlayer)
--------------------------------------------------------------------------------
/Chapter04/B06246_04_03-CellSize.py:
--------------------------------------------------------------------------------
1 | # Get the Cell Size of a Raster Layer
2 |
3 | # https://github.com/GeospatialPython/Learn/raw/master/SatImage.zip
4 |
5 | rasterLyr = QgsRasterLayer("/qgis_data/rasters/satimage.tif", "Sat Image")
6 | rasterLyr.isValid()
7 | # True
8 | rasterLyr.rasterUnitsPerPixelX()
9 | # 0.00029932313140079714
10 | rasterLyr.rasterUnitsPerPixelY()
11 | # 0.00029932313140079714
--------------------------------------------------------------------------------
/Chapter04/B06246_04_04-WidthHeight.py:
--------------------------------------------------------------------------------
1 | # Obtaining the Width and Height of a Raster
2 |
3 | # https://github.com/GeospatialPython/Learn/raw/master/SatImage.zip
4 |
5 | rasterLyr = QgsRasterLayer("/qgis_data/rasters/satimage.tif", "Satellite Image")
6 | rasterLyr.isValid()
7 | # True
8 | rasterLyr.width()
9 | # 2592
10 | rasterLyr.height()
11 | # 2693
--------------------------------------------------------------------------------
/Chapter04/B06246_04_05-CountingBands.py:
--------------------------------------------------------------------------------
1 | # Counting Raster Bands
2 |
3 | # https://github.com/GeospatialPython/Learn/raw/master/SatImage.zip
4 |
5 | rasterLyr = QgsRasterLayer("/qgis_data/rasters/satimage.tif", "Sat Image")
6 | rasterLyr.isValid()
7 | # True
8 | rasterLyr.bandCount()
9 | # 3
10 |
--------------------------------------------------------------------------------
/Chapter04/B06246_04_06-SwapBands.py:
--------------------------------------------------------------------------------
1 | # Swapping Raster Bands
2 |
3 | https://github.com/GeospatialPython/Learn/raw/master/FalseColor.zip
4 |
5 | rasterLyr = QgsRasterLayer("/qgis_data/rasters/FalseColor.tif", "Band Swap")
6 | rasterLyr.isValid()
7 | # True
8 | ren = rasterLyr.renderer()
9 | ren.setRedBand(2)
10 | ren.setGreenBand(1)
11 | QgsMapLayerRegistry.instance().addMapLayers([rasterLyr])
12 | # Blue and green image
13 |
14 |
--------------------------------------------------------------------------------
/Chapter04/B06246_04_07-QueryPoint.py:
--------------------------------------------------------------------------------
1 | # Query the Value of a Raster at a Specified Point
2 |
3 | # https://github.com/GeospatialPython/Learn/raw/master/SatImage.zip
4 |
5 | rasterLyr = QgsRasterLayer("/qgis_data/rasters/satimage.tif", "Sat Image")
6 | rasterLyr.isValid()
7 | c = rasterLyr.extent().center()
8 | qry = rasterLyr.dataProvider().identify(QgsPoint(*c), QgsRaster.IdentifyFormatValue)
9 | qry.isValid()
10 | #True
11 | qry.results()
12 | # {1: 17.0, 2: 66.0, 3: 56.0}
13 |
14 |
--------------------------------------------------------------------------------
/Chapter04/B06246_04_08-Reproject.py:
--------------------------------------------------------------------------------
1 | # Reprojecting a Raster
2 |
3 | # https://github.com/GeospatialPython/Learn/raw/master/SatImage.zip
4 |
5 | import processing
6 | rasterLyr = QgsRasterLayer("/qgis_data/rasters/SatImage.tif", "Reproject")
7 | rasterLyr.isValid()
8 | # True
9 | processing.runalg("gdalogr:warpreproject","C:/qgis_data/rasters/SatImage.tif","EPSG:4326","EPSG:3722","0",0,1,None,None,0,4,75,6,1,False,0,False,"","/qgis_data/rasters/warped.tif")
10 |
11 |
--------------------------------------------------------------------------------
/Chapter04/B06246_04_09-Hillshade.py:
--------------------------------------------------------------------------------
1 | # Creating an Elevation Hillshade
2 |
3 | # https://github.com/GeospatialPython/Learn/raw/master/dem.zip
4 |
5 | import processing
6 | rasterLyr = QgsRasterLayer("/qgis_data/rasters/dem.asc", "Hillshade")
7 | rasterLyr.isValid()
8 | # True
9 | processing.runandload("gdalogr:hillshade", rasterLyr, 1, False, False, 1.0, 1.0, 315.0, 45.0, "/qgis_data/rasters/hillshade.tif")
10 |
11 |
12 |
--------------------------------------------------------------------------------
/Chapter04/B06246_04_10-Contours.py:
--------------------------------------------------------------------------------
1 | # Creating Vector Contours from Elevation Data
2 |
3 | # https://github.com/GeospatialPython/Learn/raw/master/dem.zip
4 |
5 | import processing
6 | rasterLyr = QgsRasterLayer("/qgis_data/rasters/dem.asc", "DEM")
7 | rasterLyr.isValid()
8 | # True
9 | QgsMapLayerRegistry.instance().addMapLayers([rasterLyr])
10 | processing.runandload("gdalogr:contour", rasterLyr, 50.0, "Elv", None, "/qgis_data/rasters/contours.shp")
11 |
12 |
--------------------------------------------------------------------------------
/Chapter04/B06246_04_11-GridSample.py:
--------------------------------------------------------------------------------
1 | # Sampling Raster Dataset Using a Regular Grid
2 |
3 | # https://github.com/GeospatialPython/Learn/raw/master/SatImage.zip
4 |
5 | import numpy
6 | from PyQt4.QtCore import *
7 |
8 |
9 | spacing = .1
10 | inset = .04
11 | rasterLyr = QgsRasterLayer("/qgis_data/rasters/satimage.tif", "Sat Image")
12 | rasterLyr.isValid()
13 | # True
14 | rpr = rasterLyr.dataProvider()
15 | epsg = rasterLyr.crs().postgisSrid()
16 | ext = rasterLyr.extent()
17 | vectorLyr = QgsVectorLayer('Point?crs=epsg:%s' % epsg, 'Grid' , "memory")
18 | vpr = vectorLyr.dataProvider()
19 | qd = QVariant.Double
20 | vpr.addAttributes([QgsField("Red", qd), QgsField("Green", qd), QgsField("Blue", qd)])
21 | vectorLyr.updateFields()
22 | xmin = ext.xMinimum() + inset
23 | xmax = ext.xMaximum()
24 | ymin = ext.yMinimum() + inset
25 | ymax = ext.yMaximum() - inset
26 |
27 | pts = [(x,y) for x in (i for i in numpy.arange(xmin, xmax, spacing)) for y in (j for j in numpy.arange(ymin, ymax, spacing))]
28 | feats = []
29 | for x,y in pts:
30 | f = QgsFeature()
31 | p = QgsPoint(x,y)
32 | qry = rasterLyr.dataProvider().identify(p, QgsRaster.IdentifyFormatValue)
33 | r = qry.results()
34 | f.setAttribute(0, r[1])
35 | f.setAttribute(1, r[2])
36 | f.setAttribute(2, r[3])
37 | f.setGeometry(QgsGeometry.fromPoint(p))
38 | feats.append(f)
39 | vpr.addFeatures(feats)
40 | vectorLyr.updateExtents()
41 | QgsMapLayerRegistry.instance().addMapLayers([vectorLyr, rasterLyr])
42 | canvas = qgis.utils.iface.mapCanvas()
43 | canvas.setExtent(rasterLyr.extent())
44 | canvas.refresh()
45 |
46 |
47 |
48 |
49 |
50 |
--------------------------------------------------------------------------------
/Chapter04/B06246_04_12-PointDEM.py:
--------------------------------------------------------------------------------
1 | # Adding Elevation Data to Line Vertices using a DEM
2 |
3 | # https://github.com/GeospatialPython/Learn/raw/master/path.zip
4 |
5 | import processing
6 | from PyQt4.QtCore import *
7 |
8 | pth = "/qgis_data/rasters/path/"
9 | rasterPth = pth + "elevation.asc"
10 | vectorPth = pth + "paths.shp"
11 | pointsPth = pth + "points.shp"
12 | elvPointsPth = pth + "elvPoints.shp"
13 |
14 | settings = QSettings()
15 | originalSetting = settings.value("/Projections/defaultBehaviour", "prompt", type=str)
16 | settings.setValue("/Projections/defaultBehaviour", "useProject")
17 |
18 | rasterLyr = QgsRasterLayer(rasterPth, "Elevation")
19 | crs = QgsCoordinateReferenceSystem()
20 | crs.createFromSrid(4326)
21 | rasterLyr.setCrs(crs)
22 | settings.setValue( "/Projections/defaultBehaviour", originalSetting)
23 |
24 | rasterLyr.isValid()
25 | # True
26 |
27 |
28 | vectorLyr = QgsVectorLayer(vectorPth, "Path", "ogr")
29 | vectorLyr.isValid()
30 | # True
31 |
32 | QgsMapLayerRegistry.instance().addMapLayers([rasterLyr])
33 |
34 | QgsMapLayerRegistry.instance().addMapLayers([vectorLyr, rasterLyr])
35 | processing.runalg("saga:convertlinestopoints", vectorLyr, False, 1, pointsPth)
36 | processing.runandload("saga:addgridvaluestopoints", pointsPth, rasterPth, 0, elvPointsPth)
37 |
--------------------------------------------------------------------------------
/Chapter04/B06246_04_13-CommExt.py:
--------------------------------------------------------------------------------
1 | # Creating a Common Extent for Rasters
2 |
3 | # https://github.com/GeospatialPython/Learn/raw/master/overlap.zip
4 | # https://github.com/GeospatialPython/Learn/raw/master/unify_extents.zip
5 |
6 | import processing
7 |
8 | processing.runalg("script:unifyextentandresolution","/qgis_data/rasters/Image2.tif;/qgis_data/rasters/Image1.tif",-9999,"/qgis_data/rasters",True)
--------------------------------------------------------------------------------
/Chapter04/B06246_04_14-Resample.py:
--------------------------------------------------------------------------------
1 | # Resampling Raster Resolution
2 |
3 | # https://github.com/GeospatialPython/Learn/raw/master/SatImage.zip
4 |
5 | import processing
6 | rasterLyr = QgsRasterLayer("/qgis_data/rasters/SatImage.tif", "Resample")
7 | rasterLyr.isValid()
8 | # True
9 | epsg = rasterLyr.crs().postgisSrid()
10 | srs = "EPSG:%s" % epsg
11 | res = rasterLyr.rasterUnitsPerPixelX() * 2
12 | processing.runalg("gdalogr:warpreproject",rasterLyr,srs,srs,res,0,0,None,"EPSG:4326",5,4,75,6,1,False,0,False,"","/qgis_data/rasters/resampled.tif")
13 |
14 |
--------------------------------------------------------------------------------
/Chapter04/B06246_04_15-CountValues.py:
--------------------------------------------------------------------------------
1 | # Counting the Unique Values in a Raster
2 |
3 | # https://github.com/GeospatialPython/Learn/raw/master/SatImage.zip
4 |
5 | import gdalnumeric
6 | a = gdalnumeric.LoadFile("/qgis_data/rasters/satimage.tif")
7 | b = a.T.ravel()
8 | c=b.reshape((b.size/3,3))
9 | order = gdalnumeric.numpy.lexsort(c.T)
10 | c = c[order]
11 | diff = gdalnumeric.numpy.diff(c, axis=0)
12 | ui = gdalnumeric.numpy.ones(len(c), 'bool')
13 | ui[1:] = (diff != 0).any(axis=1)
14 | u = c[ui]
15 | u.size
16 |
--------------------------------------------------------------------------------
/Chapter04/B06246_04_16-Mosaic.py:
--------------------------------------------------------------------------------
1 | # Mosaicing Rasters
2 |
3 | # https://github.com/GeospatialPython/Learn/raw/master/overlap.zip
4 |
5 | processing.runalg("gdalogr:merge","/qgis_data/rasters/Image2.tif;/qgis_data/rasters/Image1.tif",False,False,0,"/qgis_data/rasters/merged.tif")
--------------------------------------------------------------------------------
/Chapter04/B06246_04_17-TIFF2JPG.py:
--------------------------------------------------------------------------------
1 | # Converting a TIFF Image to a JPEG Image
2 |
3 | # https://github.com/GeospatialPython/Learn/raw/master/SatImage.zip
4 |
5 | from osgeo import gdal
6 | drv = gdal.GetDriverByName("JP2OpenJPEG")
7 | src = gdal.Open("/qgis_data/rasters/satimage.tif")
8 | tgt = drv.CreateCopy("/qgis_data/rasters/satimage.jp2", src)
--------------------------------------------------------------------------------
/Chapter04/B06246_04_18-Pyramids.py:
--------------------------------------------------------------------------------
1 | # Creating Pyramids for a Raster
2 |
3 | # https://github.com/GeospatialPython/Learn/raw/master/FalseColor.zip
4 |
5 | import processing
6 |
7 | processing.runalg("gdalogr:overviews","/qgis_data/rasters/FalseColor.tif","2 4 8 16",True,0,1)
8 |
--------------------------------------------------------------------------------
/Chapter04/B06246_04_19-Pixel2World.py:
--------------------------------------------------------------------------------
1 | # Converting a Pixel Location to a Geospatial Coordinate
2 |
3 | # https://github.com/GeospatialPython/Learn/raw/master/SatImage.zip
4 |
5 | from osgeo import gdal
6 |
7 | def Pixel2world(geoMatrix, x, y):
8 | ulX = geoMatrix[0]
9 | ulY = geoMatrix[3]
10 | xDist = geoMatrix[1]
11 | yDist = geoMatrix[5]
12 | coorX = (ulX + (x * xDist))
13 | coorY = (ulY + (y * yDist))
14 | return (coorX, coorY)
15 |
16 | src = gdal.Open("/qgis_data/rasters/satimage.tif")
17 | geoTrans = src.GetGeoTransform()
18 | centerX = src.RasterXSize/2
19 | centerY = src.RasterYSize/2
20 | Pixel2world(geoTrans, centerX, centerY)
21 | #(-89.59486002580364, 30.510227817850406)
22 |
23 |
--------------------------------------------------------------------------------
/Chapter04/B06246_04_20-World2Pixel.py:
--------------------------------------------------------------------------------
1 | # Converting a Geospatial Coordinate to a Pixel Location
2 |
3 | # https://github.com/GeospatialPython/Learn/raw/master/SatImage.zip
4 |
5 | from osgeo import gdal
6 |
7 | def world2Pixel(geoMatrix, x, y):
8 | ulX = geoMatrix[0]
9 | ulY = geoMatrix[3]
10 | xDist = geoMatrix[1]
11 | yDist = geoMatrix[5]
12 | rtnX = geoMatrix[2]
13 | rtnY = geoMatrix[4]
14 | pixel = int((x - ulX) / xDist)
15 | line = int((y - ulY) / yDist)
16 | return (pixel, line)
17 |
18 | src = gdal.Open("/qgis_data/rasters/satimage.tif")
19 | geoTrans = src.GetGeoTransform()
20 | world2Pixel(geoTrans, -89.59486002580364, 30.510227817850406)
21 | # (1296, 1346)
22 |
23 |
--------------------------------------------------------------------------------
/Chapter04/B06246_04_21-KML.py:
--------------------------------------------------------------------------------
1 | # Creating a KML Image Overlay for a Raster
2 |
3 | # https://github.com/GeospatialPython/Learn/raw/master/SatImage.zip
4 |
5 | from osgeo import gdal
6 | import zipfile
7 |
8 | srcf = "/qgis_data/rasters/satimage.tif"
9 | vfn = "/vsimem/satimage.jpg"
10 | drv = gdal.GetDriverByName('JPEG')
11 | src = gdal.Open(srcf)
12 | tgt = drv.CreateCopy(vfn, src)
13 | rasterLyr = QgsRasterLayer(srcf, "SatImage")
14 | e = rasterLyr.extent()
15 | kml = """
16 |
17 |
18 | QGIS KML Example
19 |
20 | SatImage
21 | 30
22 |
23 | SatImage.jpg
24 |
25 |
26 | %s
27 | %s
28 | %s
29 | %s
30 |
31 |
32 |
33 | """ %(e.yMaximum(), e.yMinimum(), e.xMaximum(), e.xMinimum())
34 | vsifile = gdal.VSIFOpenL(vfn,'r')
35 | gdal.VSIFSeekL(vsifile, 0, 2)
36 | vsileng = gdal.VSIFTellL(vsifile)
37 | gdal.VSIFSeekL(vsifile, 0, 0)
38 | z = zipfile.ZipFile("/qgis_data/rasters/satimage.kmz", "w", zipfile.ZIP_DEFLATED)
39 | z.writestr("doc.kml", kml)
40 | z.writestr("SatImage.jpg", gdal.VSIFReadL(1, vsileng, vsifile))
41 | z.close()
42 |
--------------------------------------------------------------------------------
/Chapter04/B06246_04_22-Classify.py:
--------------------------------------------------------------------------------
1 | # Classifying a Raster
2 |
3 | # https://github.com/GeospatialPython/Learn/raw/master/FalseColor.zip
4 |
5 | import processing
6 | # OTB toolbox must be installed on Windows
7 | processing.runandload("otb:unsupervisedkmeansimageclassification","/qgis_data/rasters/FalseColor.tif",128,None,100,3,1000,0.95,"/qgis_data/rasters/class.tif",None)
8 |
9 |
--------------------------------------------------------------------------------
/Chapter04/B06246_04_23-Raster2Vec.py:
--------------------------------------------------------------------------------
1 | # Converting a Raster to a Vector
2 |
3 | # https://github.com/GeospatialPython/Learn/raw/master/landuse_bay.zip
4 |
5 | import processing
6 |
7 | processing.runandload("gdalogr:polygonize","/qgis_data/rasters/landuse_bay.tif","DN",None)
8 |
--------------------------------------------------------------------------------
/Chapter04/B06246_04_24-GCP.py:
--------------------------------------------------------------------------------
1 | # Georeferencing a Raster from Ground Control Points
2 |
3 | # https://github.com/GeospatialPython/Learn/raw/master/georef.zip
4 |
5 | from processing.algs.gdal.GdalUtils import GdalUtils
6 |
7 | src = "/qgis_data/rasters/georef/1853survey.jpg"
8 | points = "/qgis_data/rasters/georef/1853survey.points"
9 | trans = "/qgis_data/rasters/georef/1835survey_trans.tif"
10 | final = "/qgis_data/rasters/georef/1835survey_georef.tif"
11 |
12 | gcp = open(points, "rb")
13 | hdr = gcp.readline()
14 | command = ["gdal_translate"]
15 | for line in gcp:
16 | x,y,col,row,e = line.split(",")
17 | command.append("-gcp")
18 | command.append("%s" % col)
19 | command.append("%s" % abs(float(row)))
20 | command.append("%s" % x)
21 | command.append("%s" % y)
22 |
23 | command.append(src)
24 | command.append(trans)
25 |
26 | GdalUtils.runGdal(command, None)
27 |
28 | command = ["gdalwarp"]
29 | command.extend(["-r", "near", "-order", "3", "-co", "COMPRESS=NONE", "-dstalpha"])
30 |
31 | command.append(trans)
32 | command.append(final)
33 |
34 | GdalUtils.runGdal(command, None)
35 |
36 |
37 |
--------------------------------------------------------------------------------
/Chapter04/B06246_04_25-Clip.py:
--------------------------------------------------------------------------------
1 | # Clipping a Raster using a Shapefile
2 |
3 | # https://github.com/GeospatialPython/Learn/raw/master/SatImage.zip
4 |
5 | import processing
6 |
7 | processing.runandload("gdalogr:cliprasterbymasklayer","/qgis_data/rasters/SatImage.tif","/qgis_data/hancock/hancock.shp",None,False,False,False,0,4,75,6,1,False,0,False,"",None)
--------------------------------------------------------------------------------
/Chapter05/B06246_05_01-canvas.py:
--------------------------------------------------------------------------------
1 | # Accessing the Map Canvas
2 |
3 | canvas = qgis.utils.iface.mapCanvas()
4 | canvas.size()
5 | # PyQt4.QtCore.QSize(698, 138)
6 |
7 |
8 |
--------------------------------------------------------------------------------
/Chapter05/B06246_05_02-units.py:
--------------------------------------------------------------------------------
1 | # Change the Map Units
2 |
3 | canvas = iface.mapCanvas()
4 | canvas.mapUnits()
5 | # 2
6 | canvas.setMapUnits(0)
7 |
8 | # 0 Meters
9 | # 1 Feet
10 | # 2 Degrees
11 | # 3 UnknownUnit
12 | # 4 DecimalDegrees
13 | # 5 DegreesMinutesSeconds
14 | # 6 DegreesDecimalMinutes
15 | # 7 NauticalMiles
16 |
--------------------------------------------------------------------------------
/Chapter05/B06246_05_03-iter.py:
--------------------------------------------------------------------------------
1 | # Iterating over Layers
2 |
3 | # https://github.com/GeospatialPython/Learn/raw/master/MSCities_Geo_Pts.zip
4 | # https://github.com/GeospatialPython/Learn/raw/master/Mississippi.zip
5 |
6 | lyr_1 = QgsVectorLayer("/qgis_data/ms/mississippi.shp", "Mississippi", "ogr")
7 | lyr_2 = QgsVectorLayer("/qgis_data/ms/MSCities_Geo_Pts.shp", "Cities", "ogr")
8 | registry = QgsMapLayerRegistry.instance()
9 | registry.addMapLayers([lyr_2, lyr_1])
10 | layers = registry.mapLayers()
11 | for l in layers:
12 | print l.title()
13 |
14 | #Cities20140904160234792
15 | #Mississippi20140904160234635
16 |
17 |
--------------------------------------------------------------------------------
/Chapter05/B06246_05_04-symbol.py:
--------------------------------------------------------------------------------
1 | # Symbolizing a Vector Layer
2 |
3 | # https://github.com/GeospatialPython/Learn/raw/master/Mississippi.zip
4 |
5 | from PyQt4.QtGui import *
6 |
7 | lyr = QgsVectorLayer("/qgis_data/ms/mississippi.shp", "Mississippi", "ogr")
8 | QgsMapLayerRegistry.instance().addMapLayer(lyr)
9 | symbols = lyr.rendererV2().symbols()
10 | sym = symbols[0]
11 | sym.setColor(QColor.fromRgb(255,0,0))
12 | lyr.triggerRepaint()
13 |
14 |
--------------------------------------------------------------------------------
/Chapter05/B06246_05_05-transparentfill.py:
--------------------------------------------------------------------------------
1 | # Setting a transparent layer fill
2 |
3 | # https://github.com/GeospatialPython/Learn/raw/master/Mississippi.zip
4 |
5 | lyr = QgsVectorLayer("/qgis_data/ms/mississippi.shp", "Mississippi", "ogr")
6 | QgsMapLayerRegistry.instance().addMapLayer(lyr)
7 | properties = {}
8 | properties["color"] = '#289e26'
9 | properties["color_border"] = '#289e26'
10 | properties["width_border"] = '2'
11 | properties["style"] = 'no'
12 | sym = QgsFillSymbolV2.createSimple(properties)
13 | renderer = lyr.rendererV2()
14 | renderer.setSymbol(sym)
15 | lyr.triggerRepaint()
16 |
--------------------------------------------------------------------------------
/Chapter05/B06246_05_06-filled_marker.py:
--------------------------------------------------------------------------------
1 | # Using a filled marker symbol
2 |
3 | # https://github.com/GeospatialPython/Learn/raw/master/Mississippi.zip
4 |
5 | lyr = QgsVectorLayer("/qgis_data/ms/mississippi.shp", "Mississippi", "ogr")
6 | QgsMapLayerRegistry.instance().addMapLayer(lyr)
7 |
8 | marker_props = {}
9 | marker_props["color"] = 'red'
10 | marker_props["color_border"] = 'black'
11 | marker_props["name"] = 'star'
12 | marker_props["size"] = '3'
13 |
14 | marker = QgsMarkerSymbolV2.createSimple(marker_props)
15 |
16 | filled_marker = QgsPointPatternFillSymbolLayer()
17 |
18 | filled_marker.setDistanceX(4.0)
19 | filled_marker.setDistanceY(4.0)
20 | filled_marker.setSubSymbol(marker)
21 |
22 | renderer = lyr.rendererV2()
23 | renderer.symbols()[0].changeSymbolLayer(0, filled_marker)
24 |
25 | lyr.triggerRepaint()
26 |
27 |
--------------------------------------------------------------------------------
/Chapter05/B06246_05_07-ramp.py:
--------------------------------------------------------------------------------
1 | # Rendering a Single Band Raster Using a Color-Ramp Algorithm
2 |
3 | # https://github.com/GeospatialPython/Learn/raw/master/dem.zip
4 |
5 | from PyQt4.QtGui import QColor
6 |
7 | lyr = QgsRasterLayer("/qgis_data/rasters/dem.asc", "DEM")
8 |
9 | s = QgsRasterShader()
10 | c = QgsColorRampShader()
11 | c.setColorRampType(QgsColorRampShader.INTERPOLATED)
12 |
13 | i = []
14 | i.append(c.ColorRampItem(400, QColor('#d7191c'), '400 meters'))
15 | i.append(c.ColorRampItem(900, QColor('#fdae61'), '900 meters'))
16 | i.append(c.ColorRampItem(1500, QColor('#ffffbf'), '1500 meters'))
17 | i.append(c.ColorRampItem(2000, QColor('#abdda4'), '2000 meters'))
18 | i.append(c.ColorRampItem(2500, QColor('#2b83ba'), '2500 meters'))
19 |
20 | c.setColorRampItemList(i)
21 |
22 | s.setRasterShaderFunction(c)
23 |
24 | ps = QgsSingleBandPseudoColorRenderer(lyr.dataProvider(), 1, s)
25 |
26 | lyr.setRenderer(ps)
27 |
28 | QgsMapLayerRegistry.instance().addMapLayer(lyr)
--------------------------------------------------------------------------------
/Chapter05/B06246_05_08-csvcolor.py:
--------------------------------------------------------------------------------
1 | # Set a feature color using a column in a CSV
2 |
3 | # https://github.com/GeospatialPython/Learn/raw/master/point_colors.csv
4 |
5 | uri = "file:///qgis_data/shapes/point_colors.csv?"
6 | uri += "type=csv&"
7 | uri += "xField=X&yField=Y&"
8 | uri += "spatialIndex=no&"
9 | uri += "subsetIndex=no&"
10 | uri += "watchFile=no&"
11 | uri += "crs=epsg:4326"
12 | lyr = QgsVectorLayer(uri,"Points","delimitedtext")
13 |
14 | sym = QgsSymbolV2.defaultSymbol(lyr.geometryType())
15 | symLyr = sym.symbolLayer(0)
16 | symLyr.setDataDefinedProperty("color", '"COLOR"')
17 | lyr.rendererV2().symbols()[0].changeSymbolLayer(0, symLyr)
18 |
19 | QgsMapLayerRegistry.instance().addMapLayers([lyr])
--------------------------------------------------------------------------------
/Chapter05/B06246_05_09-complex.py:
--------------------------------------------------------------------------------
1 | # Creating a Complex Vector Layer Symbol
2 |
3 | # https://github.com/GeospatialPython/Learn/raw/master/paths.zip
4 |
5 | lyr = QgsVectorLayer("/qgis_data/shapes/paths.shp", "Route", "ogr")
6 |
7 | symbolList = lyr.rendererV2().symbols()
8 | symbol = symbolList[0]
9 |
10 | symLyrReg = QgsSymbolLayerV2Registry
11 |
12 | lineStyle = {'width':'0.26', 'color':'0,0,0'}
13 |
14 | symLyr1Meta = symLyrReg.instance().symbolLayerMetadata("SimpleLine")
15 |
16 | symLyr1 = symLyr1Meta.createSymbolLayer(lineStyle)
17 |
18 | symbol.appendSymbolLayer(symLyr1)
19 |
20 | markerStyle = {}
21 | markerStyle['width'] = '0.26'
22 | markerStyle['color'] = '0,0,0'
23 | markerStyle['interval'] = '3'
24 | markerStyle['interval_unit'] = 'MM'
25 | markerStyle['placement'] = 'interval'
26 | markerStyle['rotate'] = '1'
27 |
28 | symLyr2Meta = symLyrReg.instance().symbolLayerMetadata("MarkerLine")
29 |
30 | symLyr2 = symLyr2Meta.createSymbolLayer(markerStyle)
31 |
32 | sybSym = symLyr2.subSymbol()
33 |
34 | sybSym.deleteSymbolLayer(0)
35 |
36 | railStyle = {'size':'2', 'color':'0,0,0', 'name':'line', 'angle':'0'}
37 |
38 | railMeta = symLyrReg.instance().symbolLayerMetadata("SimpleMarker")
39 |
40 | rail = railMeta.createSymbolLayer(railStyle)
41 |
42 | sybSym.appendSymbolLayer(rail)
43 |
44 | symbol.appendSymbolLayer(symLyr2)
45 |
46 | QgsMapLayerRegistry.instance().addMapLayer(lyr)
--------------------------------------------------------------------------------
/Chapter05/B06246_05_10-icons.py:
--------------------------------------------------------------------------------
1 | # Using Icons as Vector Layer Symbols
2 |
3 | # https://github.com/GeospatialPython/Learn/raw/master/NYC_MUSEUMS_GEO.zip
4 |
5 | src = "/qgis_data/nyc/NYC_MUSEUMS_GEO.shp"
6 |
7 | lyr = QgsVectorLayer(src, "Museums", "ogr")
8 |
9 | fontStyle = {}
10 | fontStyle['color'] = '#000000'
11 | fontStyle['font'] = 'Webdings'
12 | fontStyle['chr'] = 'G'
13 | fontStyle['size'] = '6'
14 |
15 | symLyr1 = QgsFontMarkerSymbolLayerV2.create(fontStyle)
16 |
17 | lyr.rendererV2().symbols()[0].changeSymbolLayer(0, symLyr1)
18 |
19 | QgsMapLayerRegistry.instance().addMapLayer(lyr)
--------------------------------------------------------------------------------
/Chapter05/B06246_05_11-outline.py:
--------------------------------------------------------------------------------
1 | # Using an outline for font markers
2 |
3 | # https://github.com/GeospatialPython/Learn/raw/master/tourism_points.zip
4 |
5 | from PyQt4.QtGui import *
6 |
7 | src = "/qgis_data/ms/tourism_points.shp"
8 |
9 | lyr = QgsVectorLayer(src, "Points of Interest", "ogr")
10 |
11 | symLyr = QgsFontMarkerSymbolLayerV2(pointSize=16, color=QColor("cyan"))
12 |
13 | symLyr.setFontFamily("'Arial'")
14 | symLyr.setCharacter("@")
15 | symLyr.setOutlineWidth(.5)
16 | symLyr.setOutlineColor(QColor("black"))
17 |
18 | lyr.rendererV2().symbols()[0].changeSymbolLayer(0, symLyr)
19 |
20 | QgsMapLayerRegistry.instance().addMapLayer(lyr)
--------------------------------------------------------------------------------
/Chapter05/B06246_05_12-arrow.py:
--------------------------------------------------------------------------------
1 | # Using an outline for font markers
2 |
3 | # https://github.com/GeospatialPython/Learn/raw/master/countries.zip
4 |
5 | # https://github.com/GeospatialPython/Learn/raw/master/human_migration_routes.zip
6 |
7 | countries_shp = "/qgis_data/countries.shp"
8 | routes_shp = "/qgis_data/human_migration_routes.shp"
9 |
10 | countries = QgsVectorLayer(countries_shp, "Countries", "ogr")
11 | routes = QgsVectorLayer(routes_shp, "Human Migration Routes", "ogr")
12 |
13 | symLyr = QgsArrowSymbolLayer()
14 |
15 | symLyr.setIsCurved(True)
16 | symLyr.setIsRepeated(False)
17 |
18 | routes.rendererV2().symbols()[0].changeSymbolLayer(0, symLyr)
19 |
20 | QgsMapLayerRegistry.instance().addMapLayers([routes,countries])
--------------------------------------------------------------------------------
/Chapter05/B06246_05_13-graduated.py:
--------------------------------------------------------------------------------
1 | # Creating a Graduated Vector Layer Symbol
2 |
3 | # https://github.com/GeospatialPython/Learn/raw/master/MS_UrbanAnC10.zip
4 |
5 | from PyQt4.QtGui import QColor
6 |
7 | lyr = QgsVectorLayer("/qgis_data/ms/MS_UrbanAnC10.shp", "Urban Areas", "ogr")
8 |
9 | population = (
10 | ("Village", 0.0, 3159.0, "cyan"),
11 | ("Small town", 3160.0, 4388.0, "blue"),
12 | ("Town", 43889.0, 6105.0, "green"),
13 | ("City", 6106.0, 10481.0, "yellow"),
14 | ("Large City", 10482.0, 27165, "orange"),
15 | ("Metropolis", 27165.0, 1060061.0, "red"))
16 |
17 | ranges = []
18 | for label, lower, upper, color in population:
19 | sym = QgsSymbolV2.defaultSymbol(lyr.geometryType())
20 | sym.setColor(QColor(color))
21 | rng = QgsRendererRangeV2(lower, upper, sym, label)
22 | ranges.append(rng)
23 |
24 | field = "POP"
25 | renderer = QgsGraduatedSymbolRendererV2(field, ranges)
26 | lyr.setRendererV2(renderer)
27 | QgsMapLayerRegistry.instance().addMapLayer(lyr)
28 |
--------------------------------------------------------------------------------
/Chapter05/B06246_05_14-categorize.py:
--------------------------------------------------------------------------------
1 | # Creating a Categorized Vector Layer Symbol
2 |
3 | # https://github.com/GeospatialPython/Learn/raw/master/landuse_shp.zip
4 |
5 | from PyQt4.QtGui import QColor
6 |
7 | lyr = QgsVectorLayer("/qgis_data/hancock/landuse.shp", "Land Use", "ogr")
8 |
9 | landuse = {
10 | "0":("yellow", "Developed"),
11 | "1":("darkcyan", "Water"),
12 | "2":("green", "Land")}
13 |
14 | categories = []
15 | for terrain, (color, label) in landuse.items():
16 | sym = QgsSymbolV2.defaultSymbol(lyr.geometryType())
17 | sym.setColor(QColor(color))
18 | category = QgsRendererCategoryV2(terrain, sym, label)
19 | categories.append(category)
20 |
21 | field = "DN"
22 | renderer = QgsCategorizedSymbolRendererV2(field, categories)
23 | lyr.setRendererV2(renderer)
24 | QgsMapLayerRegistry.instance().addMapLayer(lyr)
25 |
26 |
27 |
--------------------------------------------------------------------------------
/Chapter05/B06246_05_15-live.py:
--------------------------------------------------------------------------------
1 | # Creating a Categorized Vector Layer Symbol
2 |
3 | # https://github.com/GeospatialPython/Learn/raw/master/Mississippi.zip
4 |
5 | from PyQt4.QtGui import *
6 |
7 | lyr = QgsVectorLayer("/qgis_data/ms/mississippi.shp", "Mississippi", "ogr")
8 |
9 | sym = lyr.rendererV2().symbols()[0]
10 |
11 | fill = QgsSimpleFillSymbolLayerV2()
12 | fill.setFillColor(QColor.fromRgb(221,239,196))
13 | fill.setOutlineColor(QColor.fromRgb(63,122,17))
14 |
15 | inner_glow = QgsInnerGlowEffect()
16 | inner_glow.setColor(QColor.fromRgb(46,129,4))
17 | inner_glow.setSpread(5.0)
18 | inner_glow_lyr = QgsSimpleFillSymbolLayerV2()
19 | inner_glow_lyr.setPaintEffect(inner_glow)
20 |
21 | drop_shadow = QgsDropShadowEffect()
22 | drop_shadow_lyr = QgsSimpleFillSymbolLayerV2()
23 | drop_shadow_lyr.setPaintEffect(drop_shadow)
24 |
25 | sym.appendSymbolLayer(drop_shadow_lyr)
26 | sym.appendSymbolLayer(fill)
27 | sym.appendSymbolLayer(inner_glow_lyr)
28 |
29 | QgsMapLayerRegistry.instance().addMapLayer(lyr)
30 |
31 |
32 |
--------------------------------------------------------------------------------
/Chapter05/B06246_05_16-shapeburst.py:
--------------------------------------------------------------------------------
1 | # Creating inverted polygon shapeburst fills
2 |
3 | # https://github.com/GeospatialPython/Learn/raw/master/hancock_land_water.zip
4 |
5 | from PyQt4.QtGui import *
6 |
7 | land = QgsVectorLayer("/qgis_data/hancock/hancock_land.shp", "Land", "ogr")
8 | water = QgsVectorLayer("/qgis_data/hancock/hancock_water.shp", "Water", "ogr")
9 |
10 | land_sym = land.rendererV2().symbols()[0]
11 | water_sym = water.rendererV2().symbols()[0]
12 |
13 | fill = QgsSimpleFillSymbolLayerV2()
14 | fill.setFillColor(QColor.fromRgb(201,204,149))
15 | fill.setOutlineColor(QColor.fromRgb(175,179,138))
16 |
17 | land_sym.changeSymbolLayer(0, fill)
18 |
19 | color1 = QColor.fromRgb(95,243,248)
20 | color2 = QColor.fromRgb(51,44,247)
21 |
22 | shapeburst = QgsShapeburstFillSymbolLayerV2(color=color1, color2=color2)
23 |
24 | water_sym.changeSymbolLayer(0, shapeburst)
25 |
26 | QgsMapLayerRegistry.instance().addMapLayers([land, water])
27 |
28 |
29 |
--------------------------------------------------------------------------------
/Chapter05/B06246_05_17-bookmark.py:
--------------------------------------------------------------------------------
1 | # Creating a Map Bookmark
2 |
3 | # https://github.com/GeospatialPython/Learn/raw/master/GIS_CensusTract.zip
4 |
5 | import sqlite3
6 | dbPath = QgsApplication.qgisUserDbFilePath()
7 | db = sqlite3.connect(dbPath)
8 | cursor = db.cursor()
9 |
10 | cursor.execute("""INSERT INTO tbl_bookmarks(
11 | bookmark_id, name, project_name,
12 | xmin, ymin, xmax, ymax,
13 | projection_srid)
14 | VALUES(NULL, "BSL", NULL,
15 | -89.51715550010032,
16 | 30.233838337125075,
17 | -89.27257255649518,
18 | 30.381717490617945,
19 | 4269)""")
20 |
21 | db.commit()
--------------------------------------------------------------------------------
/Chapter05/B06246_05_18-navigate.py:
--------------------------------------------------------------------------------
1 | # Navigating to a Map Bookmark
2 |
3 | # https://github.com/GeospatialPython/Learn/raw/master/GIS_CensusTract.zip
4 |
5 | import sqlite3
6 | dbPath = QgsApplication.qgisUserDbFilePath()
7 | db = sqlite3.connect(dbPath)
8 | cursor = db.cursor()
9 | cursor.execute("""SELECT * FROM tbl_bookmarks WHERE name='BSL'""")
10 | row = cursor.fetchone()
11 | id,mark_name,project,xmin,ymin,xmax,ymax,srid = row
12 | rect = QgsRectangle(xmin, ymin, xmax, ymax)
13 | canvas = qgis.utils.iface.mapCanvas()
14 | canvas.setExtent(rect)
15 | canvas.refresh()
16 |
17 |
18 |
--------------------------------------------------------------------------------
/Chapter05/B06246_05_19-vis.py:
--------------------------------------------------------------------------------
1 | # Setting Scale-Based Visibility for a Layer
2 |
3 | # https://github.com/GeospatialPython/Learn/raw/master/GIS_CensusTract.zip
4 |
5 | lyr = QgsVectorLayer("/qgis_data/census/GIS_CensusTract_poly.shp", "Census", "ogr")
6 |
7 | lyr.toggleScaleBasedVisibility(True)
8 |
9 | lyr.setMinimumScale(22945.0)
10 | lyr.setMaximumScale(1000000.0)
11 |
12 | QgsMapLayerRegistry.instance().addMapLayer(lyr)
--------------------------------------------------------------------------------
/Chapter05/B06246_05_20-svg.py:
--------------------------------------------------------------------------------
1 | # Using SVG for Layer Symbols
2 |
3 | # https://github.com/GeospatialPython/Learn/raw/master/NYC_MUSEUMS_GEO.zip
4 |
5 | src = "/qgis_data/nyc/NYC_MUSEUMS_GEO.shp"
6 |
7 | lyr = QgsVectorLayer(src, "Museums", "ogr")
8 |
9 | svgStyle = {}
10 | svgStyle['fill'] = '#0000ff'
11 | svgStyle['name'] = 'landmark/tourism=museum.svg'
12 | svgStyle['outline'] = '#000000'
13 | svgStyle['outline-width'] = '0'
14 | svgStyle['size'] = '6'
15 |
16 | symLyr1 = QgsSvgMarkerSymbolLayerV2.create(svgStyle)
17 |
18 | lyr.rendererV2().symbols()[0].changeSymbolLayer(0, symLyr1)
19 |
20 | QgsMapLayerRegistry.instance().addMapLayer(lyr)
--------------------------------------------------------------------------------
/Chapter05/B06246_05_21-pie.py:
--------------------------------------------------------------------------------
1 | # Using Pie Charts for Symbols
2 |
3 | # https://github.com/GeospatialPython/Learn/raw/master/County10PopnHou.zip
4 |
5 | from PyQt4.QtGui import *
6 | from PyQt4.QtCore import *
7 |
8 | # Layer
9 | lyr = QgsVectorLayer("/qgis_data/ms/County10PopnHou.shp", "Population", "ogr")
10 |
11 | # Attributes to feature in pie chart symbols
12 | categories = [u'PCT_WHT', u'PCT_BLK', u'PCT_AMIND', u'PCT_ASIAN', u'PCT_HAW', u'PCT_ORA', u'PCT_MR', u'PCT_HISP']
13 |
14 | # Colors - 1 for each attribute
15 | colors = ['#3727fa','#01daae','#f849a6','#268605','#6810ff','#453990','#630f2f','#07dd45']
16 |
17 | # Convert the colors to Qt QColor objects
18 | qcolors = map(QColor, colors)
19 |
20 | # set up our Pie Chart diagram symbol
21 | diagram = QgsPieDiagram()
22 |
23 | # Diagram settings
24 | ds = QgsDiagramSettings()
25 | ds.font = QFont("Helvetica", 12)
26 | ds.transparency = 0
27 | ds.categoryColors = qcolors
28 | ds.categoryAttributes = categories
29 | ds.categoryLabels = categories
30 | ds.size = QSizeF(100.0, 100.0)
31 | ds.sizeType = 0
32 | ds.labelPlacementMethod = 1
33 | ds.scaleByArea = True
34 | ds.minimumSize = 0
35 | ds.BackgroundColor = QColor(255,255,255,0)
36 | ds.PenColor = QColor("black")
37 | ds.penWidth = 0
38 |
39 | # Diagram Renderer
40 | dr = QgsLinearlyInterpolatedDiagramRenderer()
41 | dr.setLowerValue(0.0)
42 | dr.setLowerSize(QSizeF(0.0, 0.0))
43 | dr.setUpperValue(2000000)
44 | dr.setUpperSize(QSizeF(40,40))
45 | dr.setClassificationAttribute(6)
46 | dr.setDiagram(diagram)
47 | dr.setDiagramSettings(ds)
48 | lyr.setDiagramRenderer(dr)
49 |
50 | # Set layer-wide diagram settings
51 | dls = QgsDiagramLayerSettings()
52 | dls.dist = 0
53 | dls.priority = 0
54 | dls.xPosColumn = -1
55 | dls.yPosColumn = -1
56 | dls.placement = 0
57 | lyr.setDiagramLayerSettings(dls)
58 |
59 | # Label settings - required regardless of use
60 | label = QgsPalLayerSettings()
61 | label.readFromLayer(lyr)
62 | label.enabled = True
63 | label.writeToLayer(lyr)
64 |
65 | # Delete any cached images and repaint
66 | if hasattr(lyr, "setCacheImage"):
67 | lyr.setCacheImage(None)
68 |
69 | lyr.triggerRepaint()
70 |
71 | # Display the layer and symbols
72 | QgsMapLayerRegistry.instance().addMapLayer(lyr)
--------------------------------------------------------------------------------
/Chapter05/B06246_05_22-25D.py:
--------------------------------------------------------------------------------
1 | # Using the 2.5D Renderer
2 |
3 | # https://github.com/GeospatialPython/Learn/raw/master/buildings.zip
4 |
5 | lyr = QgsVectorLayer("/qgis_data/hancock/buildings.shp", "Buildings", "ogr")
6 | r = Qgs25DRenderer()
7 | lyr.setRendererV2(r)
8 | exp = QgsExpressionContextUtils()
9 | exp.setLayerVariable(lyr, "qgis_25d_angle", 90)
10 | exp.setLayerVariable(lyr, "qgis_25d_height", "HEIGHT")
11 | QgsMapLayerRegistry.instance().addMapLayer(lyr)
12 |
--------------------------------------------------------------------------------
/Chapter05/B06246_05_23-xyz.py:
--------------------------------------------------------------------------------
1 | # Using X,Y,Z Tiled Map Services
2 |
3 | rasterLyr = QgsRasterLayer("type=xyz&url=http://c.tile.openstreetmap.org/{z}/{x}/{y}.png", "OSM", "wms")
4 |
5 | QgsMapLayerRegistry.instance().addMapLayer(rasterLyr)
6 |
--------------------------------------------------------------------------------
/Chapter05/B06246_05_24-esri.py:
--------------------------------------------------------------------------------
1 | # Using X,Y,Z Tiled Map Services
2 |
3 | arc_map_server = "http://server.arcgisonline.com/"
4 | arc_map_server += "ArcGIS/rest/services/World_Imagery/MapServer?f=json"
5 |
6 | arc_feature_server = "https://services5.arcgis.com/U8xJBTiAx2RGR2e2"
7 | arc_feature_server += "/arcgis/rest/services/2011_Earthquakes/FeatureServer/0/"
8 | arc_feature_server += "query?outFields=*&where=1%3D1&outSR=3857&f=json"
9 |
10 | basemap = QgsRasterLayer(arc_map_server, "World Imagery")
11 |
12 | earthquakes = QgsVectorLayer(arc_feature_server, "EarthQuakes", "ogr")
13 |
14 | QgsMapLayerRegistry.instance().addMapLayers([earthquakes, basemap])
--------------------------------------------------------------------------------
/Chapter05/B06246_05_25-label.py:
--------------------------------------------------------------------------------
1 | # Label Features
2 |
3 | # https://github.com/GeospatialPython/Learn/raw/master/MSCities_Geo_Pts.zip
4 |
5 | src = "/qgis_data/ms/MSCities_Geo_Pts.shp"
6 |
7 | lyr = QgsVectorLayer(src, "Cities", "ogr")
8 |
9 | label = QgsPalLayerSettings()
10 | label.readFromLayer(lyr)
11 |
12 | label.enabled = True
13 | label.fieldName = 'NAME10'
14 | label.placement= QgsPalLayerSettings.AroundPoint
15 | label.textFont.setPointSize(12)
16 |
17 | label.writeToLayer(lyr)
18 |
19 | QgsMapLayerRegistry.instance().addMapLayers([lyr])
--------------------------------------------------------------------------------
/Chapter05/B06246_05_26-nullsym.py:
--------------------------------------------------------------------------------
1 | # Label Features
2 |
3 | # https://github.com/GeospatialPython/Learn/raw/master/MSCities_Geo_Pts.zip
4 |
5 | src = "/qgis_data/ms/MSCities_Geo_Pts.shp"
6 |
7 | lyr = QgsVectorLayer(src, "Cities", "ogr")
8 |
9 | lyr.setRendererV2(QgsNullSymbolRenderer())
10 |
11 | label = QgsPalLayerSettings()
12 | label.readFromLayer(lyr)
13 |
14 | label.enabled = True
15 | label.fieldName = 'NAME10'
16 | label.placement= QgsPalLayerSettings.AroundPoint
17 | label.setDataDefinedProperty(QgsPalLayerSettings.Size,True,True,'12','')
18 |
19 | label.writeToLayer(lyr)
20 |
21 | QgsMapLayerRegistry.instance().addMapLayers([lyr])
--------------------------------------------------------------------------------
/Chapter05/B06246_05_27-transparency.py:
--------------------------------------------------------------------------------
1 | # Change Map Layer Transparency
2 |
3 | # https://github.com/GeospatialPython/Learn/raw/master/Mississippi.zip
4 |
5 | lyr = QgsVectorLayer("/qgis_data/ms/mississippi.shp", "Mississippi", "ogr")
6 |
7 | lyr.setLayerTransparency(50)
8 |
9 | QgsMapLayerRegistry.instance().addMapLayer(lyr)
10 |
--------------------------------------------------------------------------------
/Chapter05/B06246_05_28-add.py:
--------------------------------------------------------------------------------
1 | # Adding Standard Map Tools to the Canvas
2 |
3 | # https://github.com/GeospatialPython/Learn/raw/master/Mississippi.zip
4 |
5 | from qgis.gui import *
6 | from qgis.core import *
7 | from PyQt4.QtGui import *
8 | from PyQt4.QtCore import SIGNAL, Qt
9 | import sys, os
10 |
11 | class MyWnd(QMainWindow):
12 | def __init__(self):
13 | QMainWindow.__init__(self)
14 | QgsApplication.setPrefixPath("/Applications/QGIS.app/Contents/MacOS/", True)
15 | QgsApplication.initQgis()
16 | self.canvas = QgsMapCanvas()
17 | self.canvas.setCanvasColor(Qt.white)
18 | self.lyr = QgsVectorLayer("/qgis_data/ms/mississippi.shp", "Mississippi", "ogr")
19 | QgsMapLayerRegistry.instance().addMapLayer(self.lyr)
20 | self.canvas.setExtent(self.lyr.extent())
21 | self.canvas.setLayerSet([QgsMapCanvasLayer(self.lyr)])
22 | self.setCentralWidget(self.canvas)
23 |
24 | actionZoomIn = QAction("Zoom in", self)
25 | actionZoomOut = QAction("Zoom out", self)
26 | actionPan = QAction("Pan", self)
27 |
28 | actionZoomIn.setCheckable(True)
29 | actionZoomOut.setCheckable(True)
30 | actionPan.setCheckable(True)
31 |
32 | self.connect(actionZoomIn, SIGNAL("triggered()"), self.zoomIn)
33 | self.connect(actionZoomOut, SIGNAL("triggered()"), self.zoomOut)
34 | self.connect(actionPan, SIGNAL("triggered()"), self.pan)
35 |
36 | self.toolbar = self.addToolBar("Canvas actions")
37 | self.toolbar.addAction(actionZoomIn)
38 | self.toolbar.addAction(actionZoomOut)
39 | self.toolbar.addAction(actionPan)
40 |
41 | # create the map tools
42 | self.toolPan = QgsMapToolPan(self.canvas)
43 | self.toolPan.setAction(actionPan)
44 | self.toolZoomIn = QgsMapToolZoom(self.canvas, False) # false = in
45 | self.toolZoomIn.setAction(actionZoomIn)
46 | self.toolZoomOut = QgsMapToolZoom(self.canvas, True) # true = out
47 | self.toolZoomOut.setAction(actionZoomOut)
48 |
49 | # Button selected when the application loads:
50 | self.pan()
51 |
52 | def zoomIn(self):
53 | self.canvas.setMapTool(self.toolZoomIn)
54 |
55 | def zoomOut(self):
56 | self.canvas.setMapTool(self.toolZoomOut)
57 |
58 | def pan(self):
59 | self.canvas.setMapTool(self.toolPan)
60 |
61 |
62 | class MainApp(QApplication):
63 | def __init__(self):
64 | QApplication.__init__(self,[],True)
65 | wdg = MyWnd()
66 | wdg.show()
67 | self.exec_()
68 |
69 | if __name__ == "__main__":
70 | import sys
71 | app = MainApp()
72 |
--------------------------------------------------------------------------------
/Chapter05/B06246_05_29-point.py:
--------------------------------------------------------------------------------
1 | # A Map Tool to Draw Points on the Canvas
2 |
3 | # https://github.com/GeospatialPython/Learn/raw/master/Mississippi.zip
4 |
5 | from qgis.gui import *
6 | from qgis.core import *
7 | from PyQt4.QtGui import *
8 | from PyQt4.QtCore import SIGNAL, Qt
9 | import sys, os
10 |
11 | class MyWnd(QMainWindow):
12 | def __init__(self):
13 | QMainWindow.__init__(self)
14 | QgsApplication.setPrefixPath("/Applications/QGIS.app/Contents/MacOS/", True)
15 | QgsApplication.initQgis()
16 | self.canvas = QgsMapCanvas()
17 | self.canvas.setCanvasColor(Qt.white)
18 | self.lyr = QgsVectorLayer("/qgis_data/ms/mississippi.shp", "Mississippi", "ogr")
19 | QgsMapLayerRegistry.instance().addMapLayer(self.lyr)
20 | self.canvas.setExtent(self.lyr.extent())
21 | self.canvas.setLayerSet([QgsMapCanvasLayer(self.lyr)])
22 |
23 | self.setCentralWidget(self.canvas)
24 | actionZoomIn = QAction("Zoom in", self)
25 | actionZoomOut = QAction("Zoom out", self)
26 | actionPan = QAction("Pan", self)
27 | actionPoint = QAction("Point", self)
28 |
29 | actionZoomIn.setCheckable(True)
30 | actionZoomOut.setCheckable(True)
31 | actionPan.setCheckable(True)
32 | actionPoint.setCheckable(True)
33 |
34 | self.connect(actionZoomIn, SIGNAL("triggered()"), self.zoomIn)
35 | self.connect(actionZoomOut, SIGNAL("triggered()"), self.zoomOut)
36 | self.connect(actionPan, SIGNAL("triggered()"), self.pan)
37 | self.connect(actionPoint, SIGNAL("triggered()"), self.point)
38 |
39 | self.toolbar = self.addToolBar("Canvas actions")
40 | self.toolbar.addAction(actionZoomIn)
41 | self.toolbar.addAction(actionZoomOut)
42 | self.toolbar.addAction(actionPan)
43 | self.toolbar.addAction(actionPoint)
44 |
45 | # create the map tools
46 | self.toolPan = QgsMapToolPan(self.canvas)
47 | self.toolPan.setAction(actionPan)
48 | self.toolZoomIn = QgsMapToolZoom(self.canvas, False) # false = in
49 | self.toolZoomIn.setAction(actionZoomIn)
50 | self.toolZoomOut = QgsMapToolZoom(self.canvas, True) # true = out
51 | self.toolZoomOut.setAction(actionZoomOut)
52 | self.toolPoint = PointMapTool(self.canvas)
53 | self.toolPoint.setAction(actionPoint)
54 |
55 | self.point()
56 |
57 |
58 | def zoomIn(self):
59 | self.canvas.setMapTool(self.toolZoomIn)
60 |
61 | def zoomOut(self):
62 | self.canvas.setMapTool(self.toolZoomOut)
63 |
64 | def pan(self):
65 | self.canvas.setMapTool(self.toolPan)
66 |
67 | def point(self):
68 | self.canvas.setMapTool(self.toolPoint)
69 |
70 | class PointMapTool(QgsMapToolEmitPoint):
71 | def __init__(self, canvas):
72 | self.canvas = canvas
73 | QgsMapToolEmitPoint.__init__(self, self.canvas)
74 | self.point = None
75 |
76 | def canvasPressEvent(self, e):
77 | self.point = self.toMapCoordinates(e.pos())
78 | print self.point.x(), self.point.y()
79 | m = QgsVertexMarker(self.canvas)
80 | m.setCenter(self.point)
81 | m.setColor(QColor(0,255,0))
82 | m.setIconSize(5)
83 | m.setIconType(QgsVertexMarker.ICON_BOX) # or ICON_CROSS, ICON_X
84 | m.setPenWidth(3)
85 |
86 | class MainApp(QApplication):
87 | def __init__(self):
88 | QApplication.__init__(self,[],True)
89 | wdg = MyWnd()
90 | wdg.show()
91 | self.exec_()
92 |
93 | if __name__ == "__main__":
94 | import sys
95 | app = MainApp()
96 |
97 |
--------------------------------------------------------------------------------
/Chapter05/B06246_05_30-poly.py:
--------------------------------------------------------------------------------
1 | # A Map Tool to Draw Polygons or Lines on the Canvas
2 |
3 | # https://github.com/GeospatialPython/Learn/raw/master/Mississippi.zip
4 |
5 | from qgis.gui import *
6 | from qgis.core import *
7 | from PyQt4.QtGui import *
8 | from PyQt4.QtCore import SIGNAL, Qt
9 | import sys, os
10 |
11 | class MyWnd(QMainWindow):
12 | def __init__(self):
13 | QMainWindow.__init__(self)
14 | QgsApplication.setPrefixPath("/Applications/QGIS.app/Contents/MacOS/", True)
15 | QgsApplication.initQgis()
16 | self.canvas = QgsMapCanvas()
17 | self.canvas.setCanvasColor(Qt.white)
18 | self.lyr = QgsVectorLayer("/qgis_data/ms/mississippi.shp", "Mississippi", "ogr")
19 | QgsMapLayerRegistry.instance().addMapLayer(self.lyr)
20 | self.canvas.setExtent(self.lyr.extent())
21 | self.canvas.setLayerSet([QgsMapCanvasLayer(self.lyr)])
22 |
23 | self.setCentralWidget(self.canvas)
24 | actionZoomIn = QAction("Zoom in", self)
25 | actionZoomOut = QAction("Zoom out", self)
26 | actionPan = QAction("Pan", self)
27 | actionPoly = QAction("Polygon", self)
28 |
29 | actionZoomIn.setCheckable(True)
30 | actionZoomOut.setCheckable(True)
31 | actionPan.setCheckable(True)
32 | actionPoly.setCheckable(True)
33 |
34 | self.connect(actionZoomIn, SIGNAL("triggered()"), self.zoomIn)
35 | self.connect(actionZoomOut, SIGNAL("triggered()"), self.zoomOut)
36 | self.connect(actionPan, SIGNAL("triggered()"), self.pan)
37 | self.connect(actionPoly, SIGNAL("triggered()"), self.poly)
38 |
39 | self.toolbar = self.addToolBar("Canvas actions")
40 | self.toolbar.addAction(actionZoomIn)
41 | self.toolbar.addAction(actionZoomOut)
42 | self.toolbar.addAction(actionPan)
43 | self.toolbar.addAction(actionPoly)
44 |
45 | # create the map tools
46 | self.toolPan = QgsMapToolPan(self.canvas)
47 | self.toolPan.setAction(actionPan)
48 | self.toolZoomIn = QgsMapToolZoom(self.canvas, False) # false = in
49 | self.toolZoomIn.setAction(actionZoomIn)
50 | self.toolZoomOut = QgsMapToolZoom(self.canvas, True) # true = out
51 | self.toolZoomOut.setAction(actionZoomOut)
52 | self.toolPoly = PolyMapTool(self.canvas)
53 | self.toolPoly.setAction(actionPoly)
54 |
55 | self.poly()
56 |
57 |
58 | def zoomIn(self):
59 | self.canvas.setMapTool(self.toolZoomIn)
60 |
61 | def zoomOut(self):
62 | self.canvas.setMapTool(self.toolZoomOut)
63 |
64 | def pan(self):
65 | self.canvas.setMapTool(self.toolPan)
66 |
67 | def poly(self):
68 | self.canvas.setMapTool(self.toolPoly)
69 |
70 | class PolyMapTool(QgsMapToolEmitPoint):
71 | def __init__(self, canvas):
72 | self.canvas = canvas
73 | QgsMapToolEmitPoint.__init__(self, self.canvas)
74 | self.rubberband = QgsRubberBand(self.canvas, QGis.Polygon)
75 | self.rubberband.setColor(Qt.red)
76 | self.rubberband.setWidth(1)
77 | self.point = None
78 | self.points = []
79 |
80 | def canvasPressEvent(self, e):
81 | self.point = self.toMapCoordinates(e.pos())
82 | m = QgsVertexMarker(self.canvas)
83 | m.setCenter(self.point)
84 | m.setColor(QColor(0,255,0))
85 | m.setIconSize(5)
86 | m.setIconType(QgsVertexMarker.ICON_BOX)
87 | m.setPenWidth(3)
88 | self.points.append(self.point)
89 | self.isEmittingPoint = True
90 | self.showPoly()
91 |
92 | def showPoly(self):
93 | self.rubberband.reset(QGis.Polygon)
94 | for point in self.points[:-1]:
95 | self.rubberband.addPoint(point, False)
96 | self.rubberband.addPoint(self.points[-1], True)
97 | self.rubberband.show()
98 |
99 | class MainApp(QApplication):
100 | def __init__(self):
101 | QApplication.__init__(self,[],True)
102 | wdg = MyWnd()
103 | wdg.show()
104 | self.exec_()
105 |
106 | if __name__ == "__main__":
107 | import sys
108 | app = MainApp()
109 |
110 |
111 |
--------------------------------------------------------------------------------
/Chapter05/B06246_05_31-select.py:
--------------------------------------------------------------------------------
1 | # Building a Custom Selection Tool
2 |
3 | # https://github.com/GeospatialPython/Learn/raw/master/Mississippi.zip
4 |
5 | from qgis.gui import *
6 | from qgis.core import *
7 | from PyQt4.QtGui import *
8 | from PyQt4.QtCore import SIGNAL, Qt
9 | import sys, os
10 |
11 | class MyWnd(QMainWindow):
12 | def __init__(self):
13 | QMainWindow.__init__(self)
14 | QgsApplication.setPrefixPath("/Applications/QGIS.app/Contents/MacOS/", True)
15 | QgsApplication.initQgis()
16 | self.canvas = QgsMapCanvas()
17 | self.canvas.setCanvasColor(Qt.white)
18 | self.lyr = QgsVectorLayer("/qgis_data/nyc/NYC_MUSEUMS_GEO.shp", "Mississippi", "ogr")
19 | QgsMapLayerRegistry.instance().addMapLayer(self.lyr)
20 | self.canvas.setExtent(self.lyr.extent())
21 | self.canvas.setLayerSet([QgsMapCanvasLayer(self.lyr)])
22 |
23 | self.setCentralWidget(self.canvas)
24 | actionZoomIn = QAction("Zoom in", self)
25 | actionZoomOut = QAction("Zoom out", self)
26 | actionPan = QAction("Pan", self)
27 | actionSelect = QAction("Select", self)
28 |
29 | actionZoomIn.setCheckable(True)
30 | actionZoomOut.setCheckable(True)
31 | actionPan.setCheckable(True)
32 | actionSelect.setCheckable(True)
33 |
34 | self.connect(actionZoomIn, SIGNAL("triggered()"), self.zoomIn)
35 | self.connect(actionZoomOut, SIGNAL("triggered()"), self.zoomOut)
36 | self.connect(actionPan, SIGNAL("triggered()"), self.pan)
37 | self.connect(actionSelect, SIGNAL("triggered()"), self.select)
38 |
39 | self.toolbar = self.addToolBar("Canvas actions")
40 | self.toolbar.addAction(actionZoomIn)
41 | self.toolbar.addAction(actionZoomOut)
42 | self.toolbar.addAction(actionPan)
43 | self.toolbar.addAction(actionSelect)
44 |
45 | # create the map tools
46 | self.toolPan = QgsMapToolPan(self.canvas)
47 | self.toolPan.setAction(actionPan)
48 | self.toolZoomIn = QgsMapToolZoom(self.canvas, False) # false = in
49 | self.toolZoomIn.setAction(actionZoomIn)
50 | self.toolZoomOut = QgsMapToolZoom(self.canvas, True) # true = out
51 | self.toolZoomOut.setAction(actionZoomOut)
52 | self.toolSelect = SelectMapTool(self.canvas, self.lyr)
53 | self.toolSelect.setAction(actionSelect)
54 |
55 | self.select()
56 |
57 |
58 | def zoomIn(self):
59 | self.canvas.setMapTool(self.toolZoomIn)
60 |
61 | def zoomOut(self):
62 | self.canvas.setMapTool(self.toolZoomOut)
63 |
64 | def pan(self):
65 | self.canvas.setMapTool(self.toolPan)
66 |
67 | def select(self):
68 | self.canvas.setMapTool(self.toolSelect)
69 |
70 | class SelectMapTool(QgsMapToolEmitPoint):
71 | def __init__(self, canvas, lyr):
72 | self.canvas = canvas
73 | self.lyr = lyr
74 | QgsMapToolEmitPoint.__init__(self, self.canvas)
75 | self.rubberband = QgsRubberBand(self.canvas, QGis.Polygon)
76 | self.rubberband.setColor(QColor(255,255,0,50))
77 | self.rubberband.setWidth(1)
78 | self.point = None
79 | self.points = []
80 |
81 | def canvasPressEvent(self, e):
82 | self.point = self.toMapCoordinates(e.pos())
83 | m = QgsVertexMarker(self.canvas)
84 | m.setCenter(self.point)
85 | m.setColor(QColor(0,255,0))
86 | m.setIconSize(5)
87 | m.setIconType(QgsVertexMarker.ICON_BOX)
88 | m.setPenWidth(3)
89 | self.points.append(self.point)
90 | self.isEmittingPoint = True
91 | self.selectPoly()
92 |
93 | def selectPoly(self):
94 | self.rubberband.reset(QGis.Polygon)
95 | for point in self.points[:-1]:
96 | self.rubberband.addPoint(point, False)
97 | self.rubberband.addPoint(self.points[-1], True)
98 | self.rubberband.show()
99 | if len(self.points) > 2:
100 | g = self.rubberband.asGeometry()
101 | featsPnt = self.lyr.getFeatures(QgsFeatureRequest().setFilterRect(g.boundingBox()))
102 | for featPnt in featsPnt:
103 | if featPnt.geometry().within(g):
104 | self.lyr.select(featPnt.id())
105 |
106 | class MainApp(QApplication):
107 | def __init__(self):
108 | QApplication.__init__(self,[],True)
109 | wdg = MyWnd()
110 | wdg.show()
111 | self.exec_()
112 |
113 | if __name__ == "__main__":
114 | import sys
115 | app = MainApp()
116 |
117 |
--------------------------------------------------------------------------------
/Chapter05/B06246_05_32-coord.py:
--------------------------------------------------------------------------------
1 | # Creating a Mouse Coordinate Tracking Tool
2 |
3 | # https://github.com/GeospatialPython/Learn/raw/master/Mississippi.zip
4 |
5 | from qgis.gui import *
6 | from qgis.core import *
7 | from PyQt4.QtGui import *
8 | from PyQt4.QtCore import SIGNAL, Qt, QEvent
9 | import sys, os
10 |
11 | class MyWnd(QMainWindow):
12 | def __init__(self):
13 | QMainWindow.__init__(self)
14 | QgsApplication.setPrefixPath("/Applications/QGIS.app/Contents/MacOS/", True)
15 | QgsApplication.initQgis()
16 | self.canvas = QgsMapCanvas()
17 | self.canvas.setCanvasColor(Qt.white)
18 | self.lyr = QgsVectorLayer("/qgis_data/ms/Mississippi.shp", "Mississippi", "ogr")
19 | QgsMapLayerRegistry.instance().addMapLayer(self.lyr)
20 | self.canvas.setExtent(self.lyr.extent())
21 | self.canvas.setLayerSet([QgsMapCanvasLayer(self.lyr)])
22 |
23 | self.setCentralWidget(self.canvas)
24 | actionZoomIn = QAction("Zoom in", self)
25 | actionZoomOut = QAction("Zoom out", self)
26 | actionPan = QAction("Pan", self)
27 |
28 | actionZoomIn.setCheckable(True)
29 | actionZoomOut.setCheckable(True)
30 | actionPan.setCheckable(True)
31 |
32 | self.connect(actionZoomIn, SIGNAL("triggered()"), self.zoomIn)
33 | self.connect(actionZoomOut, SIGNAL("triggered()"), self.zoomOut)
34 | self.connect(actionPan, SIGNAL("triggered()"), self.pan)
35 |
36 | self.toolbar = self.addToolBar("Canvas actions")
37 | self.toolbar.addAction(actionZoomIn)
38 | self.toolbar.addAction(actionZoomOut)
39 | self.toolbar.addAction(actionPan)
40 |
41 | # create the map tools
42 | self.toolPan = QgsMapToolPan(self.canvas)
43 | self.toolPan.setAction(actionPan)
44 | self.toolZoomIn = QgsMapToolZoom(self.canvas, False) # false = in
45 | self.toolZoomIn.setAction(actionZoomIn)
46 | self.toolZoomOut = QgsMapToolZoom(self.canvas, True) # true = out
47 | self.toolZoomOut.setAction(actionZoomOut)
48 | self.statusBar().showMessage(u"x: --, y: --")
49 |
50 | # Button selected when the application loads:
51 | self.pan()
52 |
53 | def eventFilter(self, source, event):
54 | if event.type() == QEvent.MouseMove:
55 | if event.buttons() == Qt.NoButton:
56 | pos = event.pos()
57 | x = pos.x()
58 | y = pos.y()
59 | p = self.canvas.getCoordinateTransform().toMapCoordinates(x, y)
60 | self.statusBar().showMessage(u"x: %s, y: %s" % (p.x(), p.y()))
61 | else:
62 | pass
63 | return QMainWindow.eventFilter(self, source, event)
64 |
65 | def zoomIn(self):
66 | self.canvas.setMapTool(self.toolZoomIn)
67 |
68 | def zoomOut(self):
69 | self.canvas.setMapTool(self.toolZoomOut)
70 |
71 | def pan(self):
72 | self.canvas.setMapTool(self.toolPan)
73 |
74 | class MainApp(QApplication):
75 | def __init__(self):
76 | QApplication.__init__(self,[],True)
77 | wdg = MyWnd()
78 | wdg.show()
79 | self.installEventFilter(wdg)
80 | self.exec_()
81 |
82 | if __name__ == "__main__":
83 | import sys
84 | app = MainApp()
85 |
86 |
--------------------------------------------------------------------------------
/Chapter06/B06246_06_01-renderer.py:
--------------------------------------------------------------------------------
1 | # Creating the Simplest Map Renderer
2 |
3 | # https://github.com/GeospatialPython/Learn/raw/master/hancock.zip
4 |
5 | from PyQt4.QtGui import *
6 | from PyQt4.QtCore import *
7 |
8 | lyr = QgsVectorLayer("/qgis_data/hancock/hancock.shp", "Hancock", "ogr")
9 | reg = QgsMapLayerRegistry.instance()
10 | reg.addMapLayer(lyr)
11 | i = QImage(QSize(600,600), QImage.Format_ARGB32_Premultiplied)
12 | c = QColor("white")
13 | i.fill(c.rgb())
14 | p = QPainter()
15 | p.begin(i)
16 | r = QgsMapRenderer()
17 | lyrs = reg.mapLayers().keys()
18 | r.setLayerSet(lyrs)
19 | rect = QgsRectangle(r.fullExtent())
20 | rect.scale(1.1)
21 | r.setExtent(rect)
22 | r.setOutputSize(i.size(), i.logicalDpiX())
23 | r.render(p)
24 | p.end()
25 | i.save("/qgis_data/map.jpg","jpg")
--------------------------------------------------------------------------------
/Chapter06/B06246_06_02-composer.py:
--------------------------------------------------------------------------------
1 | # Using the Map Composer
2 |
3 | # https://github.com/GeospatialPython/Learn/raw/master/hancock.zip
4 |
5 | from PyQt4.QtGui import *
6 | from PyQt4.QtCore import *
7 |
8 | lyr = QgsVectorLayer("/qgis_data/hancock/hancock.shp", "Hancock", "ogr")
9 | reg = QgsMapLayerRegistry.instance()
10 | reg.addMapLayer(lyr)
11 | lyrs = reg.mapLayers().keys()
12 | mr = iface.mapCanvas().mapRenderer()
13 | mr.setLayerSet(lyrs)
14 | rect = QgsRectangle(lyr.extent())
15 | rect.scale(1.2)
16 | mr.setExtent(rect)
17 | c = QgsComposition(mr)
18 | c.setPlotStyle(QgsComposition.Print)
19 | c.setPaperSize(215.9, 279.4)
20 | w, h = c.paperWidth() * .50, c.paperHeight() * .50
21 | x = (c.paperWidth() - w) / 2
22 | y = ((c.paperHeight() - h)) / 2
23 | composerMap = QgsComposerMap(c,x,y,w,h)
24 | composerMap.setNewExtent(rect)
25 | composerMap.setFrameEnabled(True)
26 | c.addItem(composerMap)
27 |
28 | # Set resolution
29 | dpi = c.printResolution()
30 | c.setPrintResolution(dpi)
31 | dpmm = dpi / 25.4
32 | width = int(dpmm * c.paperWidth())
33 | height = int(dpmm * c.paperHeight())
34 |
35 | # create output image and initialize it
36 | image = QImage(QSize(width, height), QImage.Format_ARGB32)
37 | image.setDotsPerMeterX(dpmm * 1000)
38 | image.setDotsPerMeterY(dpmm * 1000)
39 | image.fill(0)
40 |
41 | # render the composition
42 | imagePainter = QPainter(image)
43 | sourceArea = QRectF(0, 0, c.paperWidth(), c.paperHeight())
44 | targetArea = QRectF(0, 0, width, height)
45 | c.render(imagePainter, targetArea, sourceArea)
46 | imagePainter.end()
47 |
48 | image.save("/qgis_data/map.jpg", "jpg")
49 |
--------------------------------------------------------------------------------
/Chapter06/B06246_06_03-labels.py:
--------------------------------------------------------------------------------
1 | # Adding Labels to a Map for Printing
2 |
3 | # https://github.com/GeospatialPython/Learn/raw/master/MapComposer.py
4 | # https://github.com/GeospatialPython/Learn/raw/master/hancock.zip
5 |
6 | from PyQt4.QtCore import *
7 | from PyQt4.QtGui import *
8 | import MapComposer
9 |
10 | lyr = QgsVectorLayer("/qgis_data/hancock/hancock.shp", "Hancock", "ogr")
11 | reg = QgsMapLayerRegistry.instance()
12 | reg.addMapLayer(lyr)
13 | mr = iface.mapCanvas().mapRenderer()
14 | qc = MapComposer.MapComposer(qmlr=reg, qmr=mr)
15 | qc.label = QgsComposerLabel(qc.c)
16 | qc.label.setText("Hancock County")
17 | qc.label.adjustSizeToText()
18 | qc.label.setFrameEnabled(True)
19 | qc.label.setItemPosition(qc.x,qc.y-10)
20 | qc.c.addItem(qc.label)
21 | qc.output("/qgis_data/map.jpg", "jpg")
--------------------------------------------------------------------------------
/Chapter06/B06246_06_04-scalebar.py:
--------------------------------------------------------------------------------
1 | # Adding a Scale Bar to a Map
2 |
3 | # https://github.com/GeospatialPython/Learn/raw/master/MapComposer.py
4 | # https://github.com/GeospatialPython/Learn/raw/master/Mississippi.zip
5 |
6 | from PyQt4.QtCore import *
7 | from PyQt4.QtGui import *
8 | from qgis.core import *
9 | from qgis.gui import *
10 | import MapComposer
11 |
12 | lyr = QgsVectorLayer("/qgis_data/ms/Mississippi.shp", "Mississippi", "ogr")
13 | reg = QgsMapLayerRegistry.instance()
14 | reg.addMapLayer(lyr)
15 | mr = iface.mapCanvas().mapRenderer()
16 | qc = MapComposer.MapComposer(qmlr=reg, qmr=mr)
17 | qc.scalebar = QgsComposerScaleBar(qc.c)
18 | qc.scalebar.setStyle('Single Box')
19 | qc.scalebar.setComposerMap(qc.composerMap)
20 | qc.scalebar.applyDefaultSize()
21 | sbw = qc.scalebar.rect().width()
22 | sbh = qc.scalebar.rect().height()
23 | mcw = qc.composerMap.rect().width()
24 | mch = qc.composerMap.rect().height()
25 | sbx = qc.x + (mcw - sbw)
26 | sby = qc.y + mch
27 | qc.scalebar.setItemPosition(sbx, sby)
28 | qc.c.addItem(qc.scalebar)
29 |
30 | qc.output("/qgis_data/map.jpg", "jpg")
--------------------------------------------------------------------------------
/Chapter06/B06246_06_05-arrow.py:
--------------------------------------------------------------------------------
1 | # Adding a North Arrow to the Map
2 |
3 | # https://github.com/GeospatialPython/Learn/raw/master/MapComposer.py
4 | # https://github.com/GeospatialPython/Learn/raw/master/Mississippi.zip
5 |
6 | from PyQt4.QtCore import *
7 | from PyQt4.QtGui import *
8 | from qgis.core import *
9 | from qgis.gui import *
10 | import MapComposer
11 |
12 | lyr = QgsVectorLayer("/qgis_data/ms/Mississippi.shp", "Mississippi", "ogr")
13 | reg = QgsMapLayerRegistry.instance()
14 | reg.addMapLayer(lyr)
15 | mr = iface.mapCanvas().mapRenderer()
16 | qc = MapComposer.MapComposer(qmlr=reg, qmr=mr)
17 |
18 | mcw = qc.composerMap.rect().width()
19 | mch = qc.composerMap.rect().height()
20 | ax = qc.x + mcw + 10
21 | ay = (qc.y + mch) - 10
22 | afy = ay - 20
23 | qc.arrow = QgsComposerArrow(QPointF(ax, ay), QPointF(ax,afy), qc.c)
24 | qc.c.addItem(qc.arrow)
25 |
26 | f = QFont()
27 | f.setBold(True)
28 | f.setFamily("Times New Roman")
29 | f.setPointSize(30)
30 | qc.labelNorth = QgsComposerLabel(qc.c)
31 | qc.labelNorth.setText("N")
32 | qc.labelNorth.setFont(f)
33 | qc.labelNorth.adjustSizeToText()
34 | qc.labelNorth.setFrameEnabled(False)
35 | qc.labelNorth.setItemPosition(ax - 5, ay)
36 | qc.c.addItem(qc.labelNorth)
37 |
38 | qc.output("/qgis_data/map.jpg", "jpg")
--------------------------------------------------------------------------------
/Chapter06/B06246_06_06-logo.py:
--------------------------------------------------------------------------------
1 | # Adding a Logo to the Map
2 |
3 | # https://github.com/GeospatialPython/Learn/raw/master/MapComposer.py
4 | # https://github.com/GeospatialPython/Learn/raw/master/Mississippi.zip
5 |
6 | from PyQt4.QtCore import *
7 | from PyQt4.QtGui import *
8 | from qgis.core import *
9 | from qgis.gui import *
10 | import MapComposer
11 |
12 | lyr = QgsVectorLayer("/qgis_data/ms/mississippi.shp", "Mississippi", "ogr")
13 | reg = QgsMapLayerRegistry.instance()
14 | reg.addMapLayer(lyr)
15 | mr = iface.mapCanvas().mapRenderer()
16 | qc = MapComposer.MapComposer(qmlr=reg, qmr=mr)
17 |
18 | qc.logo = QgsComposerPicture(qc.c)
19 | qc.logo.setPictureFile("/qgis_data/rasters/logo.png")
20 | qc.logo.setSceneRect(QRectF(0,0,43,50))
21 | lx = qc.x + 50
22 | ly = qc.y - 50
23 | qc.logo.setItemPosition(lx, ly)
24 | qc.c.addItem(qc.logo)
25 |
26 | qc.output("/qgis_data/map.jpg", "jpg")
--------------------------------------------------------------------------------
/Chapter06/B06246_06_07-vlegend.py:
--------------------------------------------------------------------------------
1 | # Adding a Vertical Legend to the Map
2 |
3 | # https://github.com/GeospatialPython/Learn/raw/master/MapComposer.py
4 | # https://github.com/GeospatialPython/Learn/raw/master/Mississippi.zip
5 |
6 | from PyQt4.QtCore import *
7 | from PyQt4.QtGui import *
8 | from qgis.core import *
9 | from qgis.gui import *
10 | import MapComposer
11 |
12 | lyr = QgsVectorLayer("/qgis_data/ms/Mississippi.shp", "Mississippi", "ogr")
13 | reg = QgsMapLayerRegistry.instance()
14 | reg.addMapLayer(lyr)
15 | mr = iface.mapCanvas().mapRenderer()
16 | qc = MapComposer.MapComposer(qmlr=reg, qmr=mr)
17 |
18 | qc.legend = QgsComposerLegend(qc.c)
19 | qc.legend.model().setLayerSet(qc.qmr.layerSet())
20 | qc.legend.setItemPosition(5, qc.y)
21 | qc.c.addItem(qc.legend)
22 |
23 | qc.output("/qgis_data/map.jpg", "jpg")
--------------------------------------------------------------------------------
/Chapter06/B06246_06_07a-hlegend.py:
--------------------------------------------------------------------------------
1 | # Adding a Horizontal Legend to the Map
2 |
3 | # https://github.com/GeospatialPython/Learn/raw/master/MapComposer.py
4 | # https://github.com/GeospatialPython/Learn/raw/master/Mississippi.zip
5 | # https://github.com/GeospatialPython/Learn/raw/master/MSCities_Geo_Pts.shp
6 |
7 | from PyQt4.QtCore import *
8 | from PyQt4.QtGui import *
9 | from qgis.core import *
10 | from qgis.gui import *
11 | import MapComposer
12 |
13 | lyr = QgsVectorLayer("/qgis_data/ms/Mississippi.shp", "Mississippi", "ogr")
14 | lyr2 = QgsVectorLayer("/qgis_data/ms/MSCities_Geo_Pts.shp", "Cities", "ogr")
15 | reg = QgsMapLayerRegistry.instance()
16 | reg.addMapLayers([lyr2, lyr])
17 | mr = iface.mapCanvas().mapRenderer()
18 | qc = MapComposer.MapComposer(qmlr=reg, qmr=mr)
19 |
20 | qc.legend = QgsComposerLegend(qc.c)
21 | qc.legend.model().setLayerSet(qc.qmr.layerSet())
22 | qc.legend.setItemPosition(50,50)
23 | qc.legend.setColumnCount(2)
24 | qc.c.addItem(qc.legend)
25 |
26 | qc.output("/qgis_data/map.jpg", "jpg")
--------------------------------------------------------------------------------
/Chapter06/B06246_06_08-shape.py:
--------------------------------------------------------------------------------
1 | # Adding a Custom Shape to the Map
2 |
3 | # https://github.com/GeospatialPython/Learn/raw/master/MapComposer.py
4 | # https://github.com/GeospatialPython/Learn/raw/master/Mississippi.zip
5 |
6 | from PyQt4.QtCore import *
7 | from PyQt4.QtGui import *
8 | from qgis.core import *
9 | from qgis.gui import *
10 | import MapComposer
11 |
12 | lyr = QgsVectorLayer("/qgis_data/ms/Mississippi.shp", "Mississippi", "ogr")
13 | reg = QgsMapLayerRegistry.instance()
14 | reg.addMapLayer(lyr)
15 | mr = iface.mapCanvas().mapRenderer()
16 | qc = MapComposer.MapComposer(qmlr=reg, qmr=mr)
17 |
18 | red = {'color':'255,0,0,255','color_border':'0,0,0,255'}
19 | redsym = QgsFillSymbolV2.createSimple(red)
20 | blue = {'color':'0,0,255,255','color_border':'0,0,0,255'}
21 | bluesym = QgsFillSymbolV2.createSimple(blue)
22 | yellow = {'color':'255,255,0,255','color_border':'0,0,0,255'}
23 | yellowsym = QgsFillSymbolV2.createSimple(yellow)
24 | mch = qc.composerMap.rect().height()
25 | sy = qc.y + mch
26 | qc.shape1 = QgsComposerShape(10,sy-25,10,25,qc.c)
27 | qc.shape1.setShapeType(1)
28 | qc.shape1.setUseSymbolV2(True)
29 | qc.c.addItem(qc.shape1)
30 | qc.shape1.setShapeStyleSymbol(redsym)
31 | qc.shape2 = QgsComposerShape(22,sy-18,10,18,qc.c)
32 | qc.shape2.setShapeType(1)
33 | qc.shape2.setUseSymbolV2(True)
34 | qc.shape2.setShapeStyleSymbol(bluesym)
35 | qc.c.addItem(qc.shape2)
36 | qc.shape3 = QgsComposerShape(34,sy-12,10,12,qc.c)
37 | qc.shape3.setShapeType(1)
38 | qc.shape3.setUseSymbolV2(True)
39 | qc.shape3.setShapeStyleSymbol(yellowsym)
40 | qc.c.addItem(qc.shape3)
41 |
42 | qc.output("/qgis_data/map.jpg", "jpg")
43 |
--------------------------------------------------------------------------------
/Chapter06/B06246_06_09-grid.py:
--------------------------------------------------------------------------------
1 | # Adding a Grid to the Map
2 |
3 | # https://github.com/GeospatialPython/Learn/raw/master/MapComposer.py
4 | # https://github.com/GeospatialPython/Learn/raw/master/Mississippi.zip
5 |
6 | from PyQt4.QtCore import *
7 | from PyQt4.QtGui import *
8 | from qgis.core import *
9 | from qgis.gui import *
10 | import MapComposer
11 |
12 |
13 | lyr = QgsVectorLayer("/qgis_data/ms/Mississippi.shp", "Mississippi", "ogr")
14 | reg = QgsMapLayerRegistry.instance()
15 | reg.addMapLayer(lyr)
16 | mr = iface.mapCanvas().mapRenderer()
17 | qc = MapComposer.MapComposer(qmlr=reg, qmr=mr)
18 |
19 | # setGridAnnotationPosition method reference
20 | setGridAnnoPos = qc.composerMap.setGridAnnotationPosition
21 |
22 | # setGridAnnotationDir method reference
23 | setGridAnnoDir = qc.composerMap.setGridAnnotationDirection
24 |
25 | # QgsComposerMap
26 | qcm = QgsComposerMap
27 |
28 | # Create the map grid.
29 | qc.composerMap.setGridEnabled(True)
30 | qc.composerMap.setGridIntervalX(.75)
31 | qc.composerMap.setGridIntervalY(.75)
32 | qc.composerMap.setGridStyle(qcm.Solid)
33 | qc.composerMap.setShowGridAnnotation(True)
34 | qc.composerMap.setGridAnnotationPrecision(0)
35 |
36 |
37 | # Top
38 | setGridAnnoPos(qcm.OutsideMapFrame, qcm.Top)
39 | setGridAnnoDir(qcm.Horizontal, qcm.Top)
40 |
41 | # Bottom
42 | setGridAnnoPos(qcm.OutsideMapFrame, qcm.Bottom)
43 | setGridAnnoDir(qcm.Horizontal, qcm.Bottom)
44 |
45 | # Left
46 | setGridAnnoPos(qcm.OutsideMapFrame, qcm.Left)
47 | setGridAnnoDir(qcm.Vertical, qcm.Left)
48 |
49 | # Right
50 | setGridAnnoPos(qcm.OutsideMapFrame, qcm.Right)
51 | setGridAnnoDir(qcm.Vertical, qcm.Right)
52 |
53 | qc.composerMap.setAnnotationFrameDistance(1)
54 | qc.composerMap.setGridPenWidth(.2)
55 | qc.composerMap.setGridPenColor(QColor(0, 0, 0))
56 | qc.composerMap.setAnnotationFontColor(QColor(0, 0, 0))
57 | qc.c.addComposerMap(qc.composerMap)
58 |
59 | qc.output("/qgis_data/map.jpg", "jpg")
--------------------------------------------------------------------------------
/Chapter06/B06246_06_10-table.py:
--------------------------------------------------------------------------------
1 | # Adding a Table to the Map
2 |
3 | # https://github.com/GeospatialPython/Learn/raw/master/MapComposer.py
4 | # https://github.com/GeospatialPython/Learn/raw/master/Mississippi.zip
5 |
6 | from PyQt4.QtCore import *
7 | from PyQt4.QtGui import *
8 | from qgis.core import *
9 | from qgis.gui import *
10 | import MapComposer
11 |
12 | lyr = QgsVectorLayer("/qgis_data/ms/Mississippi.shp", "Mississippi", "ogr")
13 | reg = QgsMapLayerRegistry.instance()
14 | reg.addMapLayer(lyr)
15 | mr = iface.mapCanvas().mapRenderer()
16 | qc = MapComposer.MapComposer(qmlr=reg, qmr=mr)
17 |
18 | qc.table = QgsComposerAttributeTable(qc.c)
19 | qc.table.setComposerMap(qc.composerMap)
20 | qc.table.setVectorLayer(lyr)
21 | mch = qc.composerMap.rect().height()
22 | qc.table.setItemPosition(qc.x, qc.y + mch + 20)
23 | qc.c.addItem(qc.table)
24 |
25 | qc.output("/qgis_data/map.jpg", "jpg")
26 |
27 |
--------------------------------------------------------------------------------
/Chapter06/B06246_06_11-world_file.py:
--------------------------------------------------------------------------------
1 | # Adding a World File to a Map Image
2 |
3 | # https://github.com/GeospatialPython/Learn/raw/master/MapComposer.py
4 | # https://github.com/GeospatialPython/Learn/raw/master/Mississippi.zip
5 |
6 | from PyQt4.QtCore import *
7 | from PyQt4.QtGui import *
8 | from qgis.core import *
9 | from qgis.gui import *
10 | import MapComposer
11 |
12 | lyr = QgsVectorLayer("/qgis_data/ms/Mississippi.shp", "Mississippi", "ogr")
13 | reg = QgsMapLayerRegistry.instance()
14 | reg.addMapLayer(lyr)
15 | mr = iface.mapCanvas().mapRenderer()
16 | qc = MapComposer.MapComposer(qmlr=reg, qmr=mr)
17 |
18 | output = "/qgis_data/map"
19 | qc.output(output + ".jpg", "jpg")
20 |
21 | qc.c.setWorldFileMap(qc.composerMap)
22 | qc.c.setGenerateWorldFile(True)
23 | wf = qc.c.computeWorldFileParameters()
24 | with open(output + ".jgw", "w") as f:
25 | f.write("%s\n" % wf[0])
26 | f.write("%s\n" % wf[1])
27 | f.write("%s\n" % wf[3])
28 | f.write("%s\n" % wf[4])
29 | f.write("%s\n" % wf[2])
30 | f.write("%s\n" % wf[5])
31 |
32 |
33 |
34 |
--------------------------------------------------------------------------------
/Chapter06/B06246_06_12-save_project.py:
--------------------------------------------------------------------------------
1 | # Saving a Map to a Project
2 |
3 | # https://github.com/GeospatialPython/Learn/raw/master/Mississippi.zip
4 |
5 | from PyQt4.QtCore import *
6 |
7 | lyr = QgsVectorLayer("/qgis_data/ms/Mississippi.shp", "Mississippi", "ogr")
8 | reg = QgsMapLayerRegistry.instance()
9 | reg.addMapLayer(lyr)
10 | f = QFileInfo("/qgis_data/myProject.qgs")
11 | p = QgsProject.instance()
12 | p.write(f)
--------------------------------------------------------------------------------
/Chapter06/B06246_06_13-load_project.py:
--------------------------------------------------------------------------------
1 | # Loading a Map from a Project
2 |
3 | from PyQt4.QtCore import *
4 |
5 | f = QFileInfo("/qgis_data/myProject.qgs")
6 | p = QgsProject.instance()
7 | p.readPath("/qgis_data/")
8 | p.read(f)
--------------------------------------------------------------------------------
/Chapter06/MapComposer.py:
--------------------------------------------------------------------------------
1 |
You are being redirected.
--------------------------------------------------------------------------------
/Chapter07/4985_07_01-logs.py:
--------------------------------------------------------------------------------
1 | # Using Log Files
2 |
3 | # Settings/Options/System/Environment (use custom variables)
4 | # QGIS_LOG_FILE=/qgis_data/log.txt
5 | # Restart QGIS
6 |
7 | # Message to log file:
8 | QgsLogger.logMessageToFile("This is a message to a log file.")
9 |
10 | # Message to QGIS Log Window ( yellow triangle icon in the lower right)
11 | QgsMessageLog.logMessage("This is a message from the Python Console", "Python Console", QgsMessageLog.INFO)
--------------------------------------------------------------------------------
/Chapter07/4985_07_02-msg.py:
--------------------------------------------------------------------------------
1 | # Creating a Simple Message Dialog
2 |
3 | from PyQt4.QtGui import *
4 |
5 | msg = QMessageBox()
6 | msg.setText("This is a simple information message.")
7 | msg.exec_()
--------------------------------------------------------------------------------
/Chapter07/4985_07_03-warn.py:
--------------------------------------------------------------------------------
1 | # Creating a Warning Dialog
2 |
3 | from PyQt4.QtGui import *
4 |
5 | msg = QMessageBox()
6 | msg.setText("This is a warning...")
7 | msg.setIcon(2)
8 | msg.exec_()
9 |
10 |
11 |
--------------------------------------------------------------------------------
/Chapter07/4985_07_04-error.py:
--------------------------------------------------------------------------------
1 | # Creating an Error Dialog
2 |
3 | from PyQt4.QtGui import *
4 |
5 | msg = QMessageBox()
6 | msg.setText("This is an error!")
7 | msg.setIcon(3)
8 | msg.exec_()
--------------------------------------------------------------------------------
/Chapter07/4985_07_05-progress.py:
--------------------------------------------------------------------------------
1 | # Displaying a Progress Bar
2 |
3 | from PyQt4.QtGui import *
4 | from PyQt4.QtCore import *
5 |
6 | class Bar(QProgressBar):
7 | value = 0
8 |
9 | @pyqtSlot()
10 | def increaseValue(self):
11 | self.setValue(self.value)
12 | self.value = self.value+1
13 |
14 | bar = Bar()
15 |
16 | bar.resize(300,40)
17 | bar.setWindowTitle('Working...')
18 |
19 | timer = QTimer()
20 | bar.connect(timer,SIGNAL("timeout()"), bar, SLOT("increaseValue()"))
21 | timer.start(500)
22 |
23 | bar.show()
--------------------------------------------------------------------------------
/Chapter07/4985_07_06-text.py:
--------------------------------------------------------------------------------
1 | # Creating a Simple Text Input Dialog
2 |
3 | from PyQt4.QtGui import *
4 |
5 | qid = QInputDialog()
6 | title = "Enter Your Name"
7 | label = "Name: "
8 | mode = QLineEdit.Normal
9 | default = ""
10 |
11 | text, ok = QInputDialog.getText(qid, title, label, mode, default)
12 | print text
13 |
--------------------------------------------------------------------------------
/Chapter07/4985_07_07-file.py:
--------------------------------------------------------------------------------
1 | # Creating File Input Dialog
2 |
3 | from PyQt4.QtGui import *
4 |
5 | qfd = QFileDialog()
6 | title = 'Open File'
7 | path = "/Users/joellawhead/qgis_data"
8 |
9 | f = QFileDialog.getOpenFileName(qfd, title, path)
10 | print f
11 |
--------------------------------------------------------------------------------
/Chapter07/4985_07_08-combo.py:
--------------------------------------------------------------------------------
1 | # Creating a Combo Box
2 |
3 | from PyQt4.QtGui import *
4 |
5 | cb = QComboBox()
6 | cb.addItems(["North", "South", "West", "East"])
7 | cb.resize(200,35)
8 | cb.show()
9 | # Choose an option then execute:
10 | print cb.currentText()
11 |
--------------------------------------------------------------------------------
/Chapter07/4985_07_09-radio.py:
--------------------------------------------------------------------------------
1 | # Creating Radio Buttons
2 |
3 | from PyQt4.QtCore import *
4 | from PyQt4.QtGui import *
5 |
6 | class RadioButton(QWidget):
7 | def __init__(self, parent=None):
8 | QWidget.__init__(self, parent)
9 | self.layout = QVBoxLayout()
10 | self.rb1 = QRadioButton('Option 1')
11 | self.rb2 = QRadioButton('Option 2')
12 | self.rb3 = QRadioButton('Option 3')
13 | self.textbox = QLineEdit()
14 | self.rb1.toggled.connect(self.rb1_active)
15 | self.rb2.toggled.connect(self.rb2_active)
16 | self.rb3.toggled.connect(self.rb3_active)
17 | self.layout.addWidget(self.rb1)
18 | self.layout.addWidget(self.rb2)
19 | self.layout.addWidget(self.rb3)
20 | self.layout.addWidget(self.textbox)
21 | self.setLayout(self.layout)
22 |
23 | # First radio button selected
24 | def rb1_active(self, on):
25 | if on:
26 | self.textbox.setText('Option 1 selected')
27 |
28 | # Second radio button selected
29 | def rb2_active(self, on):
30 | if on:
31 | self.textbox.setText('Option 2 selected')
32 |
33 | # Third radio button selected
34 | def rb3_active(self, on):
35 | if on:
36 | self.textbox.setText('Option 3 selected')
37 |
38 |
39 | buttons = RadioButton()
40 | buttons.show()
--------------------------------------------------------------------------------
/Chapter07/4985_07_10-checkboxes.py:
--------------------------------------------------------------------------------
1 | # Creating Checkboxes
2 |
3 | from PyQt4.QtCore import *
4 | from PyQt4.QtGui import *
5 |
6 | class CheckBox(QWidget):
7 | def __init__(self, parent=None):
8 | QWidget.__init__(self, parent)
9 | self.layout = QVBoxLayout()
10 | self.cb1 = QCheckBox('Option 1')
11 | self.cb2 = QCheckBox('Option 2')
12 | self.cb3 = QCheckBox('Option 3')
13 | self.textbox1 = QLineEdit()
14 | self.textbox2 = QLineEdit()
15 | self.textbox3 = QLineEdit()
16 | self.cb1.toggled.connect(self.cb1_active)
17 | self.cb2.toggled.connect(self.cb2_active)
18 | self.cb3.toggled.connect(self.cb3_active)
19 | self.layout.addWidget(self.cb1)
20 | self.layout.addWidget(self.cb2)
21 | self.layout.addWidget(self.cb3)
22 | self.layout.addWidget(self.textbox1)
23 | self.layout.addWidget(self.textbox2)
24 | self.layout.addWidget(self.textbox3)
25 | self.setLayout(self.layout)
26 | # First checkbox
27 | def cb1_active(self, on):
28 | if on:
29 | self.textbox1.setText('Option 1 selected')
30 | else: self.textbox1.setText('')
31 | # Second checkbox
32 | def cb2_active(self, on):
33 | if on:
34 | self.textbox2.setText('Option 2 selected')
35 | else: self.textbox2.setText('')
36 | # Third checkbox
37 | def cb3_active(self, on):
38 | if on:
39 | self.textbox3.setText('Option 3 selected')
40 | else: self.textbox3.setText('')
41 |
42 | buttons = CheckBox()
43 | buttons.show()
--------------------------------------------------------------------------------
/Chapter07/4985_07_11-dockwidget.py:
--------------------------------------------------------------------------------
1 | # Creating a dockable widget
2 |
3 | from PyQt4.QtCore import *
4 | from PyQt4.QtGui import *
5 |
6 | te = QTextEdit("Project notes:")
7 | dw = QDockWidget("QGIS Sticky Notes")
8 | dw.setWidget(te)
9 | iface.addDockWidget(Qt.RightDockWidgetArea, dw)
--------------------------------------------------------------------------------
/Chapter07/4985_07_12-statusbar.py:
--------------------------------------------------------------------------------
1 | # Sending messages to the status bar
2 |
3 | import time
4 | iface.mainWindow().statusBar().showMessage(time.asctime())
--------------------------------------------------------------------------------
/Chapter07/4985_07_13-messagebar.py:
--------------------------------------------------------------------------------
1 | # Pushing messages to the message bar
2 |
3 | iface.messageBar().pushInfo(u'Time is running out', u'Read this quickly!')
--------------------------------------------------------------------------------
/Chapter07/4985_07_14-messagebarwidget.py:
--------------------------------------------------------------------------------
1 | # Pushing widgets to the message bar
2 |
3 | from PyQt4.QtGui import *
4 | from PyQt4.QtCore import *
5 | from qgis.gui import *
6 |
7 | class Bar(QProgressBar):
8 | value = 0
9 |
10 | @pyqtSlot()
11 | def increaseValue(self):
12 | self.setValue(self.value)
13 | self.value = self.value+1
14 |
15 | bar = Bar()
16 |
17 | bar.resize(300,40)
18 | bar.setWindowTitle('Working...')
19 |
20 | timer = QTimer()
21 | bar.connect(timer,SIGNAL("timeout()"), bar, SLOT("increaseValue()"))
22 | timer.start(100)
23 |
24 | iface.messageBar().pushWidget(bar, QgsMessageBar.INFO, 10)
25 |
--------------------------------------------------------------------------------
/Chapter07/4985_07_15-tabs.py:
--------------------------------------------------------------------------------
1 | # Creating Tabs
2 |
3 | from PyQt4.QtCore import *
4 | from PyQt4.QtGui import *
5 |
6 | qtw = QTabWidget()
7 | qtw.setWindowTitle("PyQGIS Tab Example")
8 | qtw.resize(400,300)
9 |
10 | tab1 = QWidget()
11 | tab2 = QWidget()
12 | tab3 = QWidget()
13 |
14 | layout1 = QVBoxLayout()
15 | layout1.addWidget(QTextEdit("Type text here"))
16 | tab1.setLayout(layout1)
17 |
18 | layout2 = QVBoxLayout()
19 | layout2.addWidget(QPushButton("Button"))
20 | tab2.setLayout(layout2)
21 |
22 | layout3 = QVBoxLayout()
23 | layout3.addWidget(QLabel("Label text example"))
24 | tab3.setLayout(layout3)
25 |
26 | qtw.addTab(tab1, "First Tab")
27 | qtw.addTab(tab2, "Second Tab")
28 | qtw.addTab(tab3, "Third Tab")
29 |
30 | qtw.show()
--------------------------------------------------------------------------------
/Chapter07/4985_07_16-wizard.py:
--------------------------------------------------------------------------------
1 | # Stepping the User through a Wizard
2 |
3 | from PyQt4.QtCore import *
4 | from PyQt4.QtGui import *
5 |
6 | class Page1(QWizardPage):
7 | def __init__(self, parent=None):
8 | super(Page1, self).__init__(parent)
9 | self.setTitle("What's Your Name?")
10 | self.setSubTitle("Please enter your name.")
11 | self.label = QLabel("Name:")
12 | self.uname = QLineEdit("")
13 | self.registerField("uname", self.uname)
14 | layout = QVBoxLayout()
15 | layout.addWidget(self.label)
16 | layout.addWidget(self.uname)
17 | self.setLayout(layout)
18 |
19 | class Page2(QWizardPage):
20 | def __init__(self, parent=None):
21 | super(Page2, self).__init__(parent)
22 | self.setTitle("When's Your Birthday?")
23 | self.setSubTitle("Please Select Your Birthday.")
24 | self.cal = QCalendarWidget()
25 | self.registerField("cal", self.cal, "selectedDate")
26 | layout = QVBoxLayout()
27 | layout.addWidget(self.cal)
28 | self.setLayout(layout)
29 |
30 | class Page3(QWizardPage):
31 | def __init__(self, parent=None):
32 | super(Page3, self).__init__(parent)
33 | self.setTitle("About You")
34 | self.setSubTitle("Here is Your Information:")
35 | self.name_lbl = QLabel()
36 | self.date_lbl = QLabel()
37 | layout = QVBoxLayout()
38 | layout.addWidget(self.name_lbl)
39 | layout.addWidget(self.date_lbl)
40 | self.setLayout(layout)
41 | # Initialize the page with dynamic data
42 | def initializePage(self):
43 | uname = self.field("uname")
44 | date = self.field("cal").toString()
45 | self.name_lbl.setText("Your name is %s" % uname)
46 | self.date_lbl.setText("Your birthday is %s" % date)
47 |
48 | wiz = QWizard()
49 | wiz.addPage(Page1())
50 | wiz.addPage(Page2())
51 | wiz.addPage(Page3())
52 | wiz.show()
53 |
54 |
--------------------------------------------------------------------------------
/Chapter07/4985_07_17-ontop.py:
--------------------------------------------------------------------------------
1 | # Keeping Dialogs on Top
2 |
3 | from PyQt4.QtGui import *
4 | from PyQt4.QtCore import *
5 |
6 | msg = " This window will always stay on top."
7 | lbl = QLabel(msg, None, Qt.WindowStaysOnTopHint)
8 | lbl.resize(400,400)
9 | lbl.show()
--------------------------------------------------------------------------------
/Chapter08/B06246_08_01-ndvi.py:
--------------------------------------------------------------------------------
1 | # Creating an NDVI
2 |
3 | # https://github.com/GeospatialPython/Learn/raw/master/farm-field.tif
4 |
5 | from PyQt4.QtGui import *
6 | from PyQt4.QtCore import *
7 | from qgis.analysis import *
8 |
9 | rasterName = "farm"
10 |
11 | raster = QgsRasterLayer("/qgis_data/rasters/farm-field.tif", rasterName)
12 |
13 | ir = QgsRasterCalculatorEntry()
14 | r = QgsRasterCalculatorEntry()
15 |
16 | ir.raster = raster
17 | r.raster = raster
18 |
19 | ir.bandNumber = 2
20 | r.bandNumber = 1
21 |
22 | ir.ref = rasterName + "@2"
23 | r.ref = rasterName + "@1"
24 |
25 | references = (ir.ref, r.ref, ir.ref, r.ref)
26 |
27 | exp = "1.0 * (%s - %s) / 1.0 + (%s + %s)" % references
28 |
29 | output = "/qgis_data/rasters/ndvi.tif"
30 |
31 | e = raster.extent()
32 | w = raster.width()
33 | h = raster.height()
34 |
35 | entries = [ir,r]
36 |
37 | ndvi = QgsRasterCalculator(exp, output, "GTiff", e, w, h, entries)
38 |
39 | ndvi.processCalculation()
40 |
41 |
42 | lyr = QgsRasterLayer(output, "NDVI")
43 |
44 | algorithm = QgsContrastEnhancement.StretchToMinimumMaximum
45 | limits = QgsRaster.ContrastEnhancementMinMax
46 |
47 | lyr.setContrastEnhancement(algorithm, limits)
48 |
49 | s = QgsRasterShader()
50 | c = QgsColorRampShader()
51 | c.setColorRampType(QgsColorRampShader.INTERPOLATED)
52 | i = []
53 | qri = QgsColorRampShader.ColorRampItem
54 | i.append(qri(0, QColor(0,0,0,0), 'NODATA'))
55 | i.append(qri(214, QColor(120,69,25,255), 'Lowest Biomass'))
56 | i.append(qri(236, QColor(255,178,74,255), 'Lower Biomass'))
57 | i.append(qri(258, QColor(255,237,166,255), 'Low Biomass'))
58 | i.append(qri(280, QColor(173,232,94,255), 'Moderate Biomass'))
59 | i.append(qri(303, QColor(135,181,64,255), 'High Biomass'))
60 | i.append(qri(325, QColor(3,156,0,255), 'Higher Biomass'))
61 | i.append(qri(400, QColor(1,100,0,255), 'Highest Biomass'))
62 | c.setColorRampItemList(i)
63 | s.setRasterShaderFunction(c)
64 | ps = QgsSingleBandPseudoColorRenderer(lyr.dataProvider(), 1, s)
65 | lyr.setRenderer(ps)
66 |
67 | QgsMapLayerRegistry.instance().addMapLayer(lyr)
68 |
69 |
--------------------------------------------------------------------------------
/Chapter08/B06246_08_02-geocode.py:
--------------------------------------------------------------------------------
1 | # Geocoding Addresses
2 |
3 | # Requires the QGIS Python Geocoding Plugin
4 |
5 | from GeoCoding import GeoCoding
6 | init = GeoCoding.GeoCoding(iface)
7 | from geopy.geocoders import Nominatim
8 | geocoder = Nominatim()
9 | location = geocoder.geocode("The Ugly Pirate, Bay Saint Louis, MS 39520")
10 | print location
11 |
12 |
--------------------------------------------------------------------------------
/Chapter08/B06246_08_03-raster.py:
--------------------------------------------------------------------------------
1 | ##Vector=group
2 | ##Input_Raster_Directory=folder
3 | ##Output_Footprints_Vector=output vector
4 |
5 | # QGIS Processing toolboox script to read
6 | # a directory of rasters and output a
7 | # shapefile of their footprints as polygons.
8 |
9 | # Sample data: https://github.com/GeospatialPython/Learn/raw/master/scenes.zip
10 |
11 | import os
12 | from qgis.core import *
13 |
14 | files = os.listdir(Input_Raster_Directory)
15 |
16 | footprints = []
17 |
18 | crs = ""
19 |
20 | for f in files:
21 | try:
22 | fn = os.path.join(Input_Raster_Directory, f)
23 | lyr = QgsRasterLayer(fn, "Input Raster")
24 | crs = lyr.crs()
25 | e = lyr.extent()
26 | ulx = e.xMinimum()
27 | uly = e.yMaximum()
28 | lrx = e.xMaximum()
29 | lry = e.yMinimum()
30 | ul = (ulx, uly)
31 | ur = (lrx, uly)
32 | lr = (lrx, lry)
33 | ll = (ulx, lry)
34 | fp = {}
35 | points = []
36 | points.append(QgsPoint(*ul))
37 | points.append(QgsPoint(*ur))
38 | points.append(QgsPoint(*lr))
39 | points.append(QgsPoint(*ll))
40 | points.append(QgsPoint(*ul))
41 | fp["points"] = points
42 | fp["raster"] = fn
43 | footprints.append(fp)
44 | except:
45 | progress.setInfo("Warning: The file %s does not appear to be a valid raster file." % f)
46 |
47 | vectorLyr = QgsVectorLayer("Polygon?crs=%s&field=raster:string(100)" % crs, "Footprints" , "memory")
48 |
49 | vpr = vectorLyr.dataProvider()
50 |
51 | features = []
52 |
53 | for fp in footprints:
54 | poly = QgsGeometry.fromPolygon([fp["points"]])
55 | print fp["points"]
56 | f = QgsFeature()
57 | f.setGeometry(poly)
58 | f.setAttributes([fp["raster"]])
59 | features.append(f)
60 |
61 | vpr.addFeatures(features)
62 | vectorLyr.updateExtents()
63 |
64 | driver = "Esri Shapefile"
65 |
66 | ct = QgsCoordinateTransform(crs, crs)
67 |
68 | error = QgsVectorFileWriter.writeAsVectorFormat(vectorLyr, Output_Footprints_Vector, "utf-8", ct, driver)
69 | if not QgsVectorFileWriter.NoError:
70 | progress.setInfo("Unable to output footprints.")
71 |
--------------------------------------------------------------------------------
/Chapter08/B06246_08_04-network.py:
--------------------------------------------------------------------------------
1 | # Performing Network Analysis
2 |
3 | # https://github.com/GeospatialPython/Learn/raw/master/network.zip
4 |
5 | from qgis.core import *
6 | from qgis.gui import *
7 | from qgis.networkanalysis import *
8 | from PyQt4.QtCore import *
9 |
10 | network = QgsVectorLayer("/qgis_data/shapes/Network.shp", "Network Layer", "ogr")
11 | waypoints = QgsVectorLayer("/qgis_data/shapes/NetworkPoints.shp", "Waypoints", "ogr")
12 | director = QgsLineVectorLayerDirector(network, -1, '', '', '', 3)
13 | properter = QgsDistanceArcProperter()
14 | director.addProperter(properter)
15 | crs = network.crs()
16 | builder = QgsGraphBuilder(crs)
17 |
18 | ptStart = QgsPoint(-0.8095638694, -0.1578175511)
19 | ptStop = QgsPoint(0.8907435677, 0.4430834924)
20 |
21 | tiePoints = director.makeGraph(builder, [ptStart, ptStop])
22 | graph = builder.graph()
23 |
24 | tStart = tiePoints[0]
25 | tStop = tiePoints[1]
26 |
27 | idStart = graph.findVertex(tStart)
28 | idStop = graph.findVertex(tStop)
29 |
30 | (tree, cost) = QgsGraphAnalyzer.dijkstra(graph, idStart, 0)
31 |
32 | p = []
33 | curPos = idStop
34 | while curPos != idStart:
35 | p.append(graph.vertex(graph.arc(tree[curPos]).inVertex()).point())
36 | curPos = graph.arc(tree[curPos]).outVertex()
37 |
38 | p.append(tStart)
39 | QgsMapLayerRegistry.instance().addMapLayers([network,waypoints])
40 | rb = QgsRubberBand(iface.mapCanvas())
41 | rb.setColor(Qt.red)
42 |
43 | for pnt in p:
44 | rb.addPoint(pnt)
45 |
--------------------------------------------------------------------------------
/Chapter08/B06246_08_05-routing.py:
--------------------------------------------------------------------------------
1 | # Routing along Streets
2 |
3 | # Requires the QGIS GeoSearch Plugin
4 | # Also requries the OpenLayers Plugin
5 |
6 | import qgis.utils
7 | from GeoSearch import geosearchdialog, GoogleMapsApi
8 |
9 | openLyrs = qgis.utils.plugins['openlayers_plugin']
10 |
11 | g = geosearchdialog.GeoSearchDialog(iface)
12 | g.SearchRoute([])
13 | d = GoogleMapsApi.directions.Directions()
14 |
15 | origin = "Boston, MA"
16 | dest = "2517 Main Rd, Dedham, ME 04429"
17 |
18 | route = d.GetDirections(origin, dest, mode = "driving", waypoints=None, avoid=None, units="imperial")
19 |
20 | layerType = openLyrs._olLayerTypeRegistry.getById(4)
21 | openLyrs.addLayer(layerType)
22 |
23 | g.CreateVectorLayerGeoSearch_Route(route)
--------------------------------------------------------------------------------
/Chapter08/B06246_08_06-tracking.py:
--------------------------------------------------------------------------------
1 | # Tracking a GPS
2 |
3 | import urllib
4 | import urllib2
5 | import time
6 |
7 | # Free NMEA Sample Generator
8 | url = 'http://freenmea.net/api/emitnmea'
9 | values = {'types' : 'default'}
10 | data = urllib.urlencode(values)
11 | req = urllib2.Request(url, data)
12 | results = []
13 | for i in range(10):
14 | response = urllib2.urlopen(req)
15 | results.extend(response.read().split("\n"))
16 |
17 | # World Boundaries data
18 | wb = "https://raw.githubusercontent.com/johan/world.geo.json/master/countries.geo.json"
19 | basemap = QgsVectorLayer(wb, "Countries", "ogr")
20 | qmr = QgsMapLayerRegistry.instance()
21 | qmr.addMapLayer(basemap)
22 | vectorLyr = QgsVectorLayer('Point?crs=epsg:4326', 'GPS Point' , "memory")
23 | vpr = vectorLyr.dataProvider()
24 | cLat = None
25 | cLon = None
26 | canvas = iface.mapCanvas()
27 | c = QgsNMEAConnection(None)
28 | firstPt = True
29 |
30 | for r in results:
31 | l = len(r)
32 | if "GGA" in r:
33 | c.processGGASentence(r,l)
34 | elif "RMC" in r:
35 | c.processRMCSentence(r,l)
36 | elif "GSV" in r:
37 | c.processGSVSentence(r,l)
38 | elif "VTG" in r:
39 | c.processVTGSentence(r,l)
40 | elif "GSA" in r:
41 | c.processGSASentence(r,l)
42 | i=c.currentGPSInformation()
43 | if i.latitude and i.longitude:
44 | lat = float(i.latitude)
45 | lon = float(i.longitude)
46 | if cLat is None:
47 | cLat = float(i.latitude)
48 | cLon = float(i.longitude)
49 | elif round(lat, 2)==round(cLat, 2) and round(lon, 2)==round(cLon, 2):
50 | continue
51 | else:
52 | cLat = lat
53 | cLon = lon
54 | pnt = QgsGeometry.fromPoint(QgsPoint(lon,lat))
55 | if firstPt:
56 | firstPt = False
57 | f = QgsFeature()
58 | f.setGeometry(pnt)
59 | vpr.addFeatures([f])
60 | qmr.addMapLayer(vectorLyr)
61 | else:
62 | print lon, lat
63 | vectorLyr.startEditing()
64 | vectorLyr.changeGeometry(1,pnt)
65 | vectorLyr.commitChanges()
66 | vectorLyr.setCacheImage(None)
67 | vectorLyr.updateExtents()
68 | vectorLyr.triggerRepaint()
69 | canvas.refresh()
70 | time.sleep(2)
71 |
72 |
--------------------------------------------------------------------------------
/Chapter08/B06246_08_07-mapbook.py:
--------------------------------------------------------------------------------
1 | # Creating a Mapbook
2 |
3 | # https://github.com/GeospatialPython/Learn/raw/master/countries.zip
4 |
5 | from PyQt4.QtCore import *
6 | from PyQt4.QtGui import *
7 | from qgis.core import *
8 | import PyPDF2
9 | import os
10 |
11 | filenames = []
12 | mapbook = "/qgis_data/atlas/mapbook.pdf"
13 | coverage = "/qgis_data/shapes/countries.shp"
14 | atlasPattern = "/qgis_data/atlas/output_"
15 |
16 | vlyr = QgsVectorLayer(coverage, "Countries", "ogr")
17 | QgsMapLayerRegistry.instance().addMapLayer(vlyr)
18 |
19 | mr = QgsMapRenderer()
20 | mr.setLayerSet([vlyr.id()])
21 | mr.setProjectionsEnabled(True)
22 | mr.setMapUnits(QGis.DecimalDegrees)
23 | crs = QgsCoordinateReferenceSystem()
24 | crs.createFromSrid(4326)
25 | mr.setDestinationCrs(crs)
26 |
27 | c = QgsComposition(mr)
28 | c.setPaperSize(297, 210)
29 |
30 | gray = { "color": "155,155,155" }
31 | mapSym = QgsFillSymbolV2.createSimple(gray)
32 | renderer = QgsSingleSymbolRendererV2(mapSym)
33 | vlyr.setRendererV2(renderer)
34 |
35 | atlasMap = QgsComposerMap(c, 20, 20, 130, 130)
36 | atlasMap.setFrameEnabled(True)
37 | c.addComposerMap(atlasMap)
38 |
39 | atlas = c.atlasComposition()
40 | atlas.setCoverageLayer(vlyr)
41 | atlas.setHideCoverage(False)
42 | atlas.setEnabled(True)
43 | c.setAtlasMode(QgsComposition.ExportAtlas)
44 |
45 | ov = QgsComposerMap(c, 180, 20, 50, 50)
46 | ov.setFrameEnabled(True)
47 | ov.setOverviewFrameMap(atlasMap.id())
48 | c.addComposerMap(ov)
49 | rect = QgsRectangle(vlyr.extent())
50 | ov.setNewExtent(rect)
51 |
52 | yellow = { "color": "255,255,0,255" }
53 | ovSym = QgsFillSymbolV2.createSimple(yellow)
54 | ov.setOverviewFrameMapSymbol(ovSym)
55 |
56 | lbl = QgsComposerLabel(c)
57 | c.addComposerLabel(lbl)
58 | lbl.setText("[% \"CNTRY_NAME\" %]")
59 | lbl.setFont(QgsFontUtils.getStandardTestFont())
60 | lbl.adjustSizeToText()
61 | lbl.setSceneRect(QRectF(150, 5, 60, 15))
62 |
63 | atlasMap.setAtlasDriven(True)
64 | atlasMap.setAtlasScalingMode(QgsComposerMap.Auto)
65 | atlasMap.setAtlasMargin(0.10)
66 |
67 | atlas.setFilenamePattern("'%s' || $feature" % atlasPattern)
68 | atlas.beginRender()
69 | for i in range(0, atlas.numFeatures()):
70 | atlas.prepareForFeature(i)
71 | filename = atlas.currentFilename() + ".pdf"
72 | print "Writing file %s" % filename
73 | filenames.append(filename)
74 | c.exportAsPDF(filename)
75 | atlas.endRender()
76 |
77 | output = PyPDF2.PdfFileWriter()
78 |
79 | for f in filenames:
80 | pdf = open(f, "rb")
81 | page = PyPDF2.PdfFileReader(pdf)
82 | output.addPage(page.getPage(0))
83 | os.remove(f)
84 |
85 | print "Writing final mapbook..."
86 | with open(mapbook, "wb") as book:
87 | output.write(book)
88 |
--------------------------------------------------------------------------------
/Chapter08/B06246_08_08-lcp.py:
--------------------------------------------------------------------------------
1 | # Finding the Least Cost Path
2 |
3 | # NOTE: Data must be projected
4 |
5 | # https://github.com/GeospatialPython/Learn/raw/master/lcp.zip
6 |
7 | import processing
8 |
9 | path = "/qgis_data/rasters/lcp/"
10 |
11 | # Digital Elevation Model
12 | dem = path + "dem.asc"
13 |
14 | # Starting point of our path
15 | start = path + "start-point.shp"
16 |
17 | # End of our path
18 | finish = path + "end-point.shp"
19 |
20 | # Get the DEM extent
21 | demLyr = QgsRasterLayer(dem, "DEM")
22 | ext = demLyr.extent()
23 | xmin = ext.xMinimum()
24 | ymin = ext.yMinimum()
25 | xmax = ext.xMaximum()
26 | ymax = ext.yMaximum()
27 | box = "%s,%s,%s,%s".format(xmin,xmax,ymin,ymax)
28 |
29 | a = QgsVectorLayer(start, "Start", "ogr")
30 | b = QgsVectorLayer(finish, "End", "ogr")
31 |
32 | # Cummulative cost raster to temp file
33 | cost = path + "cost.tif"
34 | tmpCost = processing.runalg("grass7:r.cost.points",dem,a,None,False,False,box,0,-1,0.0001,cost)
35 |
36 |
37 | # Merge start and end point layers into one layer for SAGA least cost path algorithm
38 | merge = path + "merge.shp"
39 | tmpMerge = processing.runalg("qgis:mergevectorlayers","{};{}".format(start,finish),merge)
40 |
41 | # Least cost path analysis
42 | vLyr = QgsVectorLayer(merge, "Destination Points", "ogr")
43 | rLyr = QgsRasterLayer(cost, "Accumulated Cost")
44 | line = path + "path.shp"
45 | points = path + "profilePts.shp"
46 | results = processing.runalg("saga:leastcostpaths",vLyr,rLyr,dem,points,line)
47 |
48 | lcp = QgsVectorLayer(line, "Least Cost Path", "ogr")
49 | QgsMapLayerRegistry.instance().addMapLayers([vLyr, lcp, demLyr])
--------------------------------------------------------------------------------
/Chapter08/B06246_08_09-nn.py:
--------------------------------------------------------------------------------
1 | # Performing Nearest Neighbor Analysis
2 |
3 | # Requires the MMQGIS Plugin
4 |
5 | # https://github.com/GeospatialPython/Learn/raw/master/ufo.zip
6 |
7 | from mmqgis import mmqgis_library as mmqgis
8 |
9 | srcPath = "/qgis_data/ufo/ufo-sightings.shp"
10 | dstPath = "/qgis_data/ufo/major-cities.shp"
11 | usPath = "/qgis_data/ufo/continental-us.shp"
12 | output = "/qgis_data/ufo/alien_invasion.shp"
13 |
14 | srcName = "UFO Sightings"
15 | dstName = "Major Cities"
16 | usName = "Continental US"
17 |
18 | source = QgsVectorLayer(srcPath, srcName, "ogr")
19 | dest = QgsVectorLayer(dstPath, dstName, "ogr")
20 | us = QgsVectorLayer(usPath, usName, "ogr")
21 | QgsMapLayerRegistry.instance().addMapLayers([source, dest, us])
22 |
23 | mmqgis.mmqgis_hub_distance(iface, srcName, dstName, "NAME", "Miles", True, output, False, True)
--------------------------------------------------------------------------------
/Chapter08/B06246_08_10-lidar.py:
--------------------------------------------------------------------------------
1 | # Converting LiDAR data to a DEM
2 |
3 | # https://github.com/GeospatialPython/Learn/raw/master/lidar.zip
4 |
5 | import processing
6 |
7 | lidar = "/qgis_data/rasters/lidar.las"
8 | output = "/qgis_data/rasters/lidar.tif"
9 |
10 | processing.runalg("lidartools:las2dem",False,False,lidar,0,1,0,0,False,"",output)
11 |
12 | lyr = QgsRasterLayer(output, "DEM")
13 |
14 | QgsMapLayerRegistry.instance().addMapLayer(lyr)
--------------------------------------------------------------------------------
/Chapter08/B06246_08_11-heatmap.py:
--------------------------------------------------------------------------------
1 | # Creating a Heat Map
2 |
3 | from PyQt4.QtCore import *
4 | from PyQt4.QtGui import *
5 | import processing
6 |
7 | countries = "https://raw.githubusercontent.com/johan/world.geo.json/"
8 | countries += "master/countries.geo.json"
9 |
10 | quakes = "https://github.com/GeospatialPython/Learn/"
11 | quakes += "raw/master/quakes2014.geojson"
12 |
13 | output = "/qgis_data/rasters/heat.tif"
14 |
15 | basemap = QgsVectorLayer(countries, "World", "ogr")
16 |
17 | quakeLyr = QgsVectorLayer(quakes, "2014 Earthquakes", "ogr")
18 |
19 | QgsMapLayerRegistry.instance().addMapLayers([quakeLyr, basemap])
20 |
21 | ext = quakeLyr.extent()
22 | xmin = ext.xMinimum()
23 | ymin = ext.yMinimum()
24 | xmax = ext.xMaximum()
25 | ymax = ext.yMaximum()
26 | box = "%s,%s,%s,%s".format(xmin,xmax,ymin,ymax)
27 |
28 | processing.runalg("saga:kerneldensityestimation",quakeLyr,"mag",10,1,box,1,0,output)
29 |
30 | heat = QgsRasterLayer(output, "Earthquake Heatmap")
31 |
32 | algorithm = QgsContrastEnhancement.StretchToMinimumMaximum
33 | limits = QgsRaster.ContrastEnhancementMinMax
34 |
35 | heat.setContrastEnhancement(algorithm, limits)
36 |
37 | s = QgsRasterShader()
38 | c = QgsColorRampShader()
39 | c.setColorRampType(QgsColorRampShader.INTERPOLATED)
40 | i = []
41 | qri = QgsColorRampShader.ColorRampItem
42 | i.append(qri(0, QColor(255,255,178,255), 'Lowest Earthquake Impact'))
43 | i.append(qri(13, QColor(254,204,92,255), 'Lower Earthquake Impact'))
44 | i.append(qri(26, QColor(253,141,60,255), 'Moderate Earthquake Impact'))
45 | i.append(qri(38, QColor(240,59,32,255), 'Higher Earthquake Impact'))
46 | i.append(qri(50, QColor(189,0,38,255), 'Highest Earthquake Impact'))
47 | c.setColorRampItemList(i)
48 | s.setRasterShaderFunction(c)
49 | ps = QgsSingleBandPseudoColorRenderer(heat.dataProvider(), 1, s)
50 | heat.setRenderer(ps)
51 |
52 | QgsMapLayerRegistry.instance().addMapLayers([heat])
53 |
54 |
--------------------------------------------------------------------------------
/Chapter08/B06246_08_12-dotdensity.py:
--------------------------------------------------------------------------------
1 | # Creating a Dot Density Map
2 |
3 | # https://github.com/GeospatialPython/Learn/raw/master/GIS_CensusTract.zip
4 |
5 | import random
6 |
7 | src = "/qgis_data/census/GIS_CensusTract_poly.shp"
8 |
9 | tractLyr = QgsVectorLayer(src, "Census Tracts", "ogr")
10 |
11 | popLyr = QgsVectorLayer('Point?crs=epsg:4326', "Population" , "memory")
12 |
13 | i = tractLyr.fieldNameIndex('POPULAT11')
14 |
15 | features = tractLyr.getFeatures()
16 |
17 | vpr = popLyr.dataProvider()
18 |
19 | dotFeatures = []
20 |
21 | for feature in features:
22 | pop = feature.attributes()[i]
23 | density = pop / 100
24 | found = 0
25 | dots = []
26 | g = feature.geometry()
27 | minx = g.boundingBox().xMinimum()
28 | miny = g.boundingBox().yMinimum()
29 | maxx = g.boundingBox().xMaximum()
30 | maxy = g.boundingBox().yMaximum()
31 | while found < density:
32 | x = random.uniform(minx,maxx)
33 | y = random.uniform(miny,maxy)
34 | pnt = QgsPoint(x,y)
35 | if g.contains(pnt):
36 | dots.append(pnt)
37 | found += 1
38 | geom = QgsGeometry.fromMultiPoint(dots)
39 | f = QgsFeature()
40 | f.setGeometry(geom)
41 | dotFeatures.append(f)
42 |
43 | vpr.addFeatures(dotFeatures)
44 | popLyr.updateExtents()
45 |
46 | QgsMapLayerRegistry.instance().addMapLayers([popLyr,tractLyr])
--------------------------------------------------------------------------------
/Chapter08/B06246_08_13-fielddata.py:
--------------------------------------------------------------------------------
1 | # Collecting Field Data
2 |
3 | # Mobile field app: http://geospatialpython.github.io/qgis/fieldwork.html
4 |
5 | wb = "https://raw.githubusercontent.com/johan/world.geo.json/master/countries.geo.json"
6 | basemap = QgsVectorLayer(wb, "Countries", "ogr")
7 | observations = QgsVectorLayer("http://bit.ly/QGISFieldApp", "Field Observations", "ogr")
8 | QgsMapLayerRegistry.instance().addMapLayers([observations, basemap])
--------------------------------------------------------------------------------
/Chapter08/B06246_08_14-slope.py:
--------------------------------------------------------------------------------
1 | # Computing Road Slope using Elevation Data
2 |
3 | # https://github.com/GeospatialPython/Learn/raw/master/road.zip
4 |
5 | from PyQt4.QtCore import *
6 | from PyQt4.QtGui import *
7 | import processing
8 |
9 | dem = "/qgis_data/road/dem.asc"
10 | road = "/qgis_data/road/road.shp"
11 | slope = "/qgis_data/road/slope.tif"
12 | segRoad = "/qgis_data/road/segRoad.shp"
13 | steepness = "/qgis_data/road/steepness.shp"
14 | hillshade = "/qgis_data/road/hillshade.tif"
15 |
16 | demLyr = QgsRasterLayer(dem, "DEM")
17 | roadLyr = QgsVectorLayer(road, "Road", "ogr")
18 |
19 | ext = demLyr.extent()
20 | xmin = ext.xMinimum()
21 | ymin = ext.yMinimum()
22 | xmax = ext.xMaximum()
23 | ymax = ext.yMaximum()
24 | demBox = "{},{},{},{}".format(xmin,xmax,ymin,ymax)
25 |
26 | processing.runalg("grass7:r.slope",dem,0,False,1,0,demBox,0,slope)
27 |
28 | ext = roadLyr.extent()
29 | xmin = ext.xMinimum()
30 | ymin = ext.yMinimum()
31 | xmax = ext.xMaximum()
32 | ymax = ext.yMaximum()
33 | roadBox = "{},{},{},{}".format(xmin,xmax,ymin,ymax)
34 |
35 | processing.runalg("grass7:v.split.length",road,500,roadBox,-1,0.0001,0,segRoad)
36 |
37 |
38 | slopeLyr = QgsRasterLayer(slope, "Slope")
39 | segRoadLyr = QgsVectorLayer(segRoad, "Segmented Road", "ogr")
40 | QgsMapLayerRegistry.instance().addMapLayers([segRoadLyr,slopeLyr], False)
41 |
42 | processing.runalg("saga:addgridvaluestoshapes",segRoad,slope,0,steepness)
43 | steepLyr = QgsVectorLayer(steepness, "Road Gradient", "ogr")
44 |
45 | roadGrade = (
46 | ("Rolling Hill", 0.0, 20.0, "green"),
47 | ("Steep", 20.0, 40.0, "yellow"),
48 | ("Very Steep", 40.0, 90.0, "red"))
49 |
50 | ranges = []
51 | for label, lower, upper, color in roadGrade:
52 | sym = QgsSymbolV2.defaultSymbol(steepLyr.geometryType())
53 | sym.setColor(QColor(color))
54 | sym.setWidth(3.0)
55 | rng = QgsRendererRangeV2(lower, upper, sym, label)
56 | ranges.append(rng)
57 |
58 | field = "slopetif"
59 | renderer = QgsGraduatedSymbolRendererV2(field, ranges)
60 | steepLyr.setRendererV2(renderer)
61 |
62 | processing.runalg("saga:analyticalhillshading",dem,0,158,45,4,hillshade)
63 |
64 | hs = QgsRasterLayer(hillshade, "Terrain")
65 |
66 | QgsMapLayerRegistry.instance().addMapLayers([steepLyr, hs])
--------------------------------------------------------------------------------
/Chapter08/B06246_08_15-geolocate.py:
--------------------------------------------------------------------------------
1 | # Geolocating Photos on the Map
2 |
3 | # https://github.com/GeospatialPython/Learn/raw/master/photos.zip
4 |
5 | import glob
6 | import Image
7 | from ExifTags import TAGS
8 |
9 | def exif(img):
10 | exif_data = {}
11 | try:
12 | i = Image.open(img)
13 | tags = i._getexif()
14 | for tag, value in tags.items():
15 | decoded = TAGS.get(tag, tag)
16 | exif_data[decoded] = value
17 | except:
18 | pass
19 | return exif_data
20 |
21 | def dms2dd(d, m, s, i):
22 | sec = float((m * 60) + s)
23 | dec = float(sec / 3600)
24 | deg = float(d + dec)
25 | if i.upper() == 'W':
26 | deg = deg * -1
27 | elif i.upper() == 'S':
28 | deg = deg * -1
29 | return float(deg)
30 |
31 | def gps(exif):
32 | lat = None
33 | lon = None
34 | if exif['GPSInfo']:
35 | # Lat
36 | coords = exif['GPSInfo']
37 | i = coords[1]
38 | d = coords[2][0][0]
39 | m = coords[2][1][0]
40 | s = coords[2][2][0]
41 | lat = dms2dd(d, m ,s, i)
42 | # Lon
43 | i = coords[3]
44 | d = coords[4][0][0]
45 | m = coords[4][1][0]
46 | s = coords[4][2][0]
47 | lon = dms2dd(d, m ,s, i)
48 | return lat, lon
49 |
50 | photos = {}
51 | photo_dir = "/qgis_data/photos/"
52 | files = glob.glob(photo_dir + "*.jpg")
53 |
54 | for f in files:
55 | e = exif(f)
56 | lat, lon = gps(e)
57 | photos[f] = [lon, lat]
58 |
59 | lyr_info = "Point?crs=epsg:4326&field=photo:string(75)"
60 |
61 | vectorLyr = QgsVectorLayer(lyr_info, "Geotagged Photos" , "memory")
62 |
63 | vpr = vectorLyr.dataProvider()
64 |
65 | features = []
66 |
67 | for pth, p in photos.items():
68 | lon, lat = p
69 | pnt = QgsGeometry.fromPoint(QgsPoint(lon,lat))
70 | f = QgsFeature()
71 | f.setGeometry(pnt)
72 | f.setAttributes([pth])
73 | features.append(f)
74 |
75 | vpr.addFeatures(features)
76 | vectorLyr.updateExtents()
77 |
78 | QgsMapLayerRegistry.instance().addMapLayer(vectorLyr)
79 | iface.setActiveLayer(vectorLyr)
80 | activeLyr = iface.activeLayer()
81 | actions = activeLyr.actions()
82 | actions.addAction(QgsAction.OpenUrl, "Photos", '[% "photo" %]')
--------------------------------------------------------------------------------
/Chapter08/B06246_08_16-change.py:
--------------------------------------------------------------------------------
1 | # Image Change Detection
2 |
3 | # https://github.com/GeospatialPython/Learn/raw/master/change-detection.zip
4 |
5 | from PyQt4.QtGui import *
6 | from PyQt4.QtCore import *
7 | from qgis.analysis import *
8 | from PyQt4.QtGui import *
9 |
10 | before = "/qgis_data/rasters/change-detection/before.tif"
11 | after = "/qgis_data/rasters/change-detection/after.tif"
12 |
13 | beforeName = "Before"
14 | afterName = "After"
15 |
16 | beforeRaster = QgsRasterLayer(before, beforeName)
17 | afterRaster = QgsRasterLayer(after, afterName)
18 |
19 | beforeEntry = QgsRasterCalculatorEntry()
20 | afterEntry = QgsRasterCalculatorEntry()
21 |
22 | beforeEntry.raster = beforeRaster
23 | afterEntry.raster = afterRaster
24 |
25 | beforeEntry.bandNumber = 1
26 | afterEntry.bandNumber = 2
27 |
28 | beforeEntry.ref = beforeName + "@1"
29 | afterEntry.ref = afterName + "@2"
30 |
31 | entries = [afterEntry, beforeEntry]
32 |
33 | exp = "%s - %s" % (afterEntry.ref, beforeEntry.ref)
34 |
35 | output = "/qgis_data/rasters/change-detection/change.tif"
36 |
37 | e = beforeRaster.extent()
38 | w = beforeRaster.width()
39 | h = beforeRaster.height()
40 |
41 | change = QgsRasterCalculator(exp, output, "GTiff", e, w, h, entries)
42 |
43 | change.processCalculation()
44 |
45 | lyr = QgsRasterLayer(output, "Change")
46 |
47 | algorithm = QgsContrastEnhancement.StretchToMinimumMaximum
48 | limits = QgsRaster.ContrastEnhancementMinMax
49 |
50 | lyr.setContrastEnhancement(algorithm, limits)
51 |
52 | s = QgsRasterShader()
53 | c = QgsColorRampShader()
54 | c.setColorRampType(QgsColorRampShader.INTERPOLATED)
55 | i = []
56 | qri = QgsColorRampShader.ColorRampItem
57 | i.append(qri(0, QColor(0,0,0,0), 'NODATA'))
58 | i.append(qri(-101, QColor(123,50,148,255), 'Significant Itensity Decrease'))
59 | i.append(qri(-42.2395, QColor(194,165,207,255), 'Minor Itensity Decrease'))
60 | i.append(qri(16.649, QColor(247,247,247,0), 'No Change'))
61 | i.append(qri(75.5375, QColor(166,219,160,255), 'Minor Itensity Increase'))
62 | i.append(qri(135, QColor(0,136,55,255), 'Significant Itensity Increase'))
63 | c.setColorRampItemList(i)
64 | s.setRasterShaderFunction(c)
65 | ps = QgsSingleBandPseudoColorRenderer(lyr.dataProvider(), 1, s)
66 | lyr.setRenderer(ps)
67 |
68 | QgsMapLayerRegistry.instance().addMapLayer(lyr)
69 |
70 |
71 |
72 |
--------------------------------------------------------------------------------
/Chapter08/B06246_08_17-irregular.py:
--------------------------------------------------------------------------------
1 | # Adjusting imprecise building footprints
2 |
3 | # Algorithm by Jose Guerrero:
4 | # http://gis.stackexchange.com/questions/212003/how-to-modify-a-polygon-to-be-more-rectangular/212325#212325
5 |
6 | # https://github.com/GeospatialPython/Learn/raw/master/irregular.zip
7 |
8 |
9 | def slope(x1, y1, x2, y2):
10 | return (y2 - y1) / (x2 - x1)
11 |
12 |
13 | def intercept(y, slope, x):
14 | return y - slope * x
15 |
16 |
17 | def perpindicular(slope):
18 | return -1 / slope
19 |
20 | pth = "/qgis_data/shapes/irregular.shp"
21 |
22 | lyr = QgsVectorLayer(pth, "Footprints", "ogr")
23 |
24 | epsg = lyr.crs().postgisSrid()
25 |
26 | uri = "Polygon?crs=epsg:{}&field=id:integer&index=yes".format(epsg)
27 |
28 | rectangle = QgsVectorLayer(uri, 'Rectangles', 'memory')
29 |
30 | p = rectangle.dataProvider()
31 |
32 | for f in lyr.getFeatures():
33 | g = f.geometry()
34 | xmin, ymin, xmax, ymax = g.boundingBox().toRectF().getCoords()
35 | pts = f.geometry().asPolygon()[0]
36 | # Find the top right point regardless of which direction
37 | # we are moving along the poly
38 | for i in range(len(pts)-1):
39 | if pts[i][1] == ymax and pts[i+1][1] < pts[i][1]:
40 | idx = i
41 | if pts[i][1] == ymax and pts[i-1][1] < pts[i][1]:
42 | idx = i-1
43 | #rectangle poly
44 | r = []
45 | #first point coords
46 | x1 = pts[idx][0]
47 | y1 = pts[idx][1]
48 | r.append(QgsPoint(x1,y1))
49 | #second point coords
50 | x2 = pts[idx+1][0]
51 | y2 = pts[idx+1][1]
52 | r.append(QgsPoint(x2,y2))
53 | #first line slope
54 | s1 = slope(x1, y1, x2, y2)
55 | #first line origin intercept
56 | i1 = intercept(y1, s1, x1)
57 | #third point coords
58 | x3 = pts[idx+2][0]
59 | y3 = pts[idx+2][1]
60 | #second line origin intercept
61 | i2 = intercept(y3, s1, x3)
62 | #first perpendicular slope
63 | s3 = perpindicular(s1)
64 | #second line origin intercept
65 | i3 = intercept(y2, s3, x2)
66 | #point intersect
67 | x4 = (i3 - i2)/(s1 - s3)
68 | y4 = s3 * x4 + i3
69 | r.append(QgsPoint(x4, y4))
70 | #second perpendicular slope
71 | s4 = perpindicular(s1)
72 | #second perpendicular origin intercept
73 | i4 = intercept(y1, s4, x1)
74 | #point intersect
75 | x5 = (i4 - i2)/(s1 - s4)
76 | y5 = s4 * x5 + i4
77 | r.extend([QgsPoint(x5, y5),QgsPoint(x1, y1)])
78 | poly = []
79 | poly.append(r)
80 | g = QgsGeometry.fromPolygon(poly)
81 | ft = QgsFeature()
82 | ft.setAttributes([i])
83 | ft.setGeometry(g)
84 | p.addFeatures([ft])
85 |
86 | QgsMapLayerRegistry.instance().addMapLayers([rectangle, lyr])
--------------------------------------------------------------------------------
/Chapter08/B06246_08_18-multitemporal.py:
--------------------------------------------------------------------------------
1 | # Visualizing Multi-temporal data
2 |
3 | # Example animation from this recipe:
4 | # http://geospatialpython.github.io/qgis/earthquake_loop.gif
5 |
6 | from PyQt4.QtGui import *
7 | from timemanager import *
8 |
9 | iface.mapCanvas().setCanvasColor(QColor(196,229,248))
10 | iface.mapCanvas().refresh()
11 |
12 | countries = "https://raw.githubusercontent.com/"
13 | countries += "johan/world.geo.json/master/countries.geo.json"
14 |
15 | quakes = "https://raw.githubusercontent.com/GeospatialPython/Learn/"
16 | quakes += "master/2011_Earthquakes.geojson"
17 |
18 | basemap = QgsVectorLayer(countries, "World", "ogr")
19 |
20 | gray = {"color": "220,221,222"}
21 | mapSym = QgsFillSymbolV2.createSimple(gray)
22 | renderer = QgsSingleSymbolRendererV2(mapSym)
23 | basemap.setRendererV2(renderer)
24 |
25 | quakeLyr = QgsVectorLayer(quakes, "2011 Earthquakes", "ogr")
26 |
27 | quakeLyr.setLayerTransparency(30)
28 |
29 | magnitude = (
30 | ("Light", 4.5, 4.7, "253,255,22", "2"),
31 | ("Moderate", 4.7, 5.0, "253,190,22", "5"),
32 | ("Strong", 5.0, 5.4, "253,122,22", "7.5"),
33 | ("Major", 5.4, 6.2, "253,99,22", "9.75"),
34 | ("Great", 6.2, 7.2, "253,0,22", "12"))
35 |
36 | ranges = []
37 | for label, lower, upper, color, size in magnitude:
38 | props = {}
39 | props["color"] = color
40 | props["size"] = size
41 | props["outline_width"] = "0"
42 | props["outline_color"] ="0,0,0,0"
43 | sym = QgsMarkerSymbolV2.createSimple(props)
44 | rng = QgsRendererRangeV2(lower, upper, sym, label)
45 | ranges.append(rng)
46 |
47 | field = "Magnitude"
48 | renderer = QgsGraduatedSymbolRendererV2(field, ranges)
49 | quakeLyr.setRendererV2(renderer)
50 |
51 | QgsMapLayerRegistry.instance().addMapLayers([quakeLyr, basemap])
52 |
53 |
54 | settings = layer_settings.LayerSettings()
55 | settings.layer = quakeLyr
56 | settings.startTimeAttribute = "Date"
57 | settings.endTimeAttribute = "Date"
58 | timeLayer = timevectorlayer.TimeVectorLayer(settings, iface=iface)
59 |
60 | try:
61 | ctrl = qgis.utils.plugins['timemanager'].getController()
62 | except:
63 | # MacOS needs the capitalized name
64 | ctrl = qgis.utils.plugins['TimeManager'].getController()
65 |
66 | tlm = ctrl.getTimeLayerManager()
67 | tlm.registerTimeLayer(timeLayer)
68 | tlm.setTimeFrameType('months')
69 | ctrl.setLoopAnimation(True)
70 | start = time_util.str_to_datetime(timeLayer.getMinMaxValues()[0])
71 | end = time_util.str_to_datetime(timeLayer.getMinMaxValues()[1])
72 | tlm.setCurrentTimePosition(start)
73 | ctrl.setAnimationFrameLength(1000)
74 | ctrl.toggleAnimation()
75 |
--------------------------------------------------------------------------------
/Chapter09/B06246_09_01-tiles.py:
--------------------------------------------------------------------------------
1 | # Creating Tiles from a QGIS Map
2 |
3 | # https://github.com/GeospatialPython/Learn/raw/master/countries.zip
4 |
5 | # Requires QMetaTiles plugin
6 |
7 | from PyQt4.QtCore import *
8 | from PyQt4.QtGui import *
9 | import QMetaTiles
10 | import random
11 |
12 | def randomColor(mix=(255,255,255)):
13 | red = random.randrange(0,256)
14 | green = random.randrange(0,256)
15 | blue = random.randrange(0,256)
16 | r,g,b = mix
17 | red = (red + r) / 2
18 | green = (green + g) / 2
19 | blue = (blue + b) / 2
20 | return (red, green, blue)
21 |
22 | def done():
23 | print "FINISHED!!"
24 |
25 | shp = "/qgis_data/shapes/countries.shp"
26 |
27 | dir = "/qgis_data/tilecache"
28 |
29 | layer = QgsVectorLayer(shp, "Countries", "ogr")
30 |
31 | field = 'CNTRY_NAME'
32 |
33 | features = layer.getFeatures()
34 |
35 | categories = []
36 |
37 | for feature in features:
38 | country = feature[field]
39 | sym = QgsSymbolV2.defaultSymbol(layer.geometryType())
40 | r,g,b = randomColor()
41 | sym.setColor(QColor(r,g,b,255))
42 | category = QgsRendererCategoryV2(country, sym, country)
43 | categories.append(category)
44 |
45 | renderer = QgsCategorizedSymbolRendererV2(field, categories)
46 | layer.setRendererV2(renderer)
47 | QgsMapLayerRegistry.instance().addMapLayer(layer)
48 |
49 | canvas = iface.mapCanvas()
50 | layers = canvas.mapSettings().layers()
51 | extent = canvas.extent()
52 | minZoom = 0
53 | maxZoom = 5
54 | width = 256
55 | height = 256
56 | transp = 100
57 | quality = 70
58 | format = "PNG"
59 | outputPath = QFileInfo(dir)
60 | rootDir = "countries"
61 | antialiasing = False
62 | tmsConvention = True
63 | mapUrl = False
64 | viewer = True
65 |
66 | tt = QMetaTiles.tilingthread.TilingThread(layers, extent, minZoom,
67 | maxZoom, width, height,
68 | transp, quality, format,
69 | outputPath, rootDir, antialiasing,
70 | tmsConvention, mapUrl, viewer,
71 | False, None, False, None)
72 |
73 | tt.processFinished.connect(done)
74 |
75 | tt.start()
76 |
--------------------------------------------------------------------------------
/Chapter09/B06246_09_02-cloud.py:
--------------------------------------------------------------------------------
1 | # Adding a layer to geojson.io
2 |
3 | # Requires qgisio plugin (experimental)
4 |
5 | from PyQt4.QtCore import *
6 | from PyQt4.QtGui import *
7 | from qgis.core import *
8 | from tempfile import mkstemp
9 | import os
10 | from qgisio import geojsonio
11 |
12 | layer = QgsVectorLayer("/qgis_data/shapes/building.shp", "Building", "ogr")
13 |
14 | name = layer.name()
15 |
16 | handle, tmpfile = mkstemp(suffix='.geojson')
17 | os.close(handle)
18 |
19 | crs = QgsCoordinateReferenceSystem(4326,
20 | QgsCoordinateReferenceSystem.PostgisCrsId)
21 | error = QgsVectorFileWriter.writeAsVectorFormat(layer, tmpfile,
22 | "utf-8", crs, "GeoJSON", onlySelected=False)
23 |
24 | if error != QgsVectorFileWriter.NoError:
25 | print "Unable to write geoJSON!"
26 |
27 | with open(str(tmpfile), 'r') as f:
28 | contents = f.read()
29 |
30 | os.remove(tmpfile)
31 |
32 | url = geojsonio._create_gist(contents, "Layer exported from QGIS", name + ".geojson")
33 |
34 | QDesktopServices.openUrl(QUrl(url))
35 |
36 |
37 |
38 |
39 |
--------------------------------------------------------------------------------
/Chapter09/B06246_09_03-rules.py:
--------------------------------------------------------------------------------
1 | # Rendering Map Layers Based on Rules
2 |
3 | # https://github.com/GeospatialPython/Learn/raw/master/ms_rails_mstm.zip
4 |
5 | from PyQt4.QtGui import *
6 |
7 | prefix = "/qgis_data/ms/"
8 |
9 | rails = QgsVectorLayer(prefix + "ms_rails_mstm.shp", "Railways", "ogr")
10 |
11 | # define some rules: label, exp, color name, (min scale, max scale)
12 | rules = (
13 | ('Heavily Used', '"DEN09CODE" > 3', 'red', (0, 6000000)),
14 | ('Moderately Used', '"DEN09CODE" < 4 AND "DEN09CODE" > 1', 'orange', (0, 1500000)),
15 | ('Lightly Used', '"DEN09CODE" < 2', 'grey', (0, 250000)),
16 | )
17 |
18 | # create a new rule-based renderer
19 | sym_rails = QgsSymbolV2.defaultSymbol(rails.geometryType())
20 | rend_rails = QgsRuleBasedRendererV2(sym_rails)
21 |
22 | # get the "root" rule
23 | root_rule = rend_rails.rootRule()
24 |
25 | for label, exp, color, scale in rules:
26 | # create a clone (i.e. a copy) of the default rule
27 | rule = root_rule.children()[0].clone()
28 | # set the label, exp and color
29 | rule.setLabel(label)
30 | rule.setFilterExpression(exp)
31 | rule.symbol().setColor(QColor(color))
32 | # set the scale limits if they have been specified
33 | if scale is not None:
34 | rule.setScaleMinDenom(scale[0])
35 | rule.setScaleMaxDenom(scale[1])
36 | # append the rule to the list of rules
37 | root_rule.appendChild(rule)
38 |
39 | # delete the default rule
40 | root_rule.removeChildAt(0)
41 |
42 | # apply the rend_rails to the rails
43 | rails.setRendererV2(rend_rails)
44 |
45 | jax = QgsVectorLayer(prefix + "jackson.shp", "Jackson", "ogr")
46 | jax_style = {}
47 | jax_style['color'] = "#ffff00"
48 | jax_style['name'] = 'regular_star'
49 | jax_style['outline'] = '#000000'
50 | jax_style['outline-width'] = '1'
51 | jax_style['size'] = '8'
52 | sym_jax = QgsSimpleMarkerSymbolLayerV2.create(jax_style)
53 | jax.rendererV2().symbols()[0].changeSymbolLayer(0, sym_jax)
54 |
55 | ms = QgsVectorLayer(prefix + "mississippi.shp", "Mississippi", "ogr")
56 | ms_style = {}
57 | ms_style['color'] = "#F7F5EB"
58 | sym_ms = QgsSimpleFillSymbolLayerV2.create(ms_style)
59 | ms.rendererV2().symbols()[0].changeSymbolLayer(0, sym_ms)
60 |
61 | QgsMapLayerRegistry.instance().addMapLayers([jax, rails, ms])
--------------------------------------------------------------------------------
/Chapter09/B06246_09_04-layerdef.py:
--------------------------------------------------------------------------------
1 | # Creating a Layer Definition File
2 |
3 | from PyQt4.QtCore import *
4 | from PyQt4.QtGui import *
5 |
6 | hs = QgsRasterLayer("/qgis_data/saveqml/hillshade.tif", "Hillshade")
7 | dem = QgsRasterLayer("/qgis_data/saveqml/dem.asc", "DEM")
8 |
9 | algorithm = QgsContrastEnhancement.StretchToMinimumMaximum
10 | limits = QgsRaster.ContrastEnhancementMinMax
11 |
12 | dem.setContrastEnhancement(algorithm, limits)
13 |
14 | s = QgsRasterShader()
15 | c = QgsColorRampShader()
16 | c.setColorRampType(QgsColorRampShader.INTERPOLATED)
17 | i = []
18 | qri = QgsColorRampShader.ColorRampItem
19 | i.append(qri(356.334, QColor(63,159,152,255), '356.334'))
20 | i.append(qri(649.292, QColor(96,235,155,255), '649.292'))
21 | i.append(qri(942.25, QColor(100,246,174,255), '942.25'))
22 | i.append(qri(1235.21, QColor(248,251,155,255), '1235.21'))
23 | i.append(qri(1528.17, QColor(246,190,39,255), '1528.17'))
24 | i.append(qri(1821.13, QColor(242,155,39,255), '1821.13'))
25 | i.append(qri(2114.08, QColor(165,84,26,255), '2114.08'))
26 | i.append(qri(2300, QColor(236,119,83,255), '2300'))
27 | i.append(qri(2700, QColor(203,203,203,255), '2700'))
28 | c.setColorRampItemList(i)
29 | s.setRasterShaderFunction(c)
30 | ps = QgsSingleBandPseudoColorRenderer(dem.dataProvider(), 1, s)
31 | ps.setOpacity(0.5)
32 | dem.setRenderer(ps)
33 |
34 | QgsMapLayerRegistry.instance().addMapLayers([dem, hs])
35 |
36 | dem.saveNamedStyle("/qgis_data/saveqml/dem.qml")
37 |
--------------------------------------------------------------------------------
/Chapter09/B06246_09_05-null.py:
--------------------------------------------------------------------------------
1 | # Using NULL Values in PyQGIS
2 |
3 | # https://github.com/GeospatialPython/Learn/raw/master/NullExample.zip
4 |
5 | lyrPth = "/qgis_data/shapes/NullExample.shp"
6 |
7 | lyr = QgsVectorLayer(lyrPth, "Null Field Example", "ogr")
8 |
9 | features = lyr.getFeatures()
10 |
11 | f = features.next()
12 |
13 | value = f["SAMPLE"]
14 |
15 | print "Check python value type:"
16 | print type(value)
17 | #
18 |
19 | print "Check python string representation:"
20 | print value
21 | # NULL
22 |
23 | print "Check if value is None:"
24 | print value is None
25 | # False
26 |
27 | print "Check if value == None:"
28 | print value == None
29 | # True
30 |
31 | print "Check if value == NULL:"
32 | print value == NULL
33 | # True
34 |
35 | print "Check if value is NULL:"
36 | print value is NULL
37 | # False
38 |
39 | print "Check type(value) is type(NULL):"
40 | print type(value) is type(NULL)
41 | # True
42 |
43 |
--------------------------------------------------------------------------------
/Chapter09/B06246_09_06-genquery.py:
--------------------------------------------------------------------------------
1 | # Using Generators for Layer Queries
2 |
3 | # easy_install https://github.com/GeospatialPython/qquery/archive/master.zip
4 |
5 | from query import query
6 |
7 | pth = "/qgis_data/ms/MS_UrbanAnC10.shp"
8 | layer = QgsVectorLayer(pth, "Urban Areas", "ogr")
9 |
10 | q = (query(layer).where("POP > 50000").select('NAME10', "POP", "AREALAND", "POPDEN"))
11 |
12 | q().next()
13 |
14 |
--------------------------------------------------------------------------------
/Chapter09/B06246_09_07-alpha.py:
--------------------------------------------------------------------------------
1 | # Using Alpha Values to Show Data Density
2 |
3 | # Requires MMQGIS Plugin
4 |
5 | # https://github.com/GeospatialPython/Learn/raw/master/bear-data.zip
6 |
7 | import processing
8 | from PyQt4.QtGui import *
9 | from mmqgis import mmqgis_library as mmqgis
10 |
11 | dir = "/qgis_data/ms/"
12 | source = dir + "bear-data.shp"
13 | grid = dir + "grid.shp"
14 | clipped_grid = dir + "clipped_grid.shp"
15 | output = dir + "ms-bear-sightings.shp"
16 |
17 | layer = QgsVectorLayer(source, "bear data", "ogr")
18 |
19 | e = layer.extent()
20 | minx = e.xMinimum()
21 | miny = e.yMinimum()
22 | maxx = e.xMaximum()
23 | maxy = e.yMaximum()
24 | w = e.width()
25 | h = e.height()
26 |
27 | crs = layer.crs()
28 |
29 | mmqgis.mmqgis_grid(iface, "Hexagons", crs, .1, .1, minx, miny, maxx, maxy, "Hexagon (polygon)", grid, False)
30 |
31 | processing.runalg("qgis:clip",grid,source,clipped_grid)
32 |
33 | processing.runalg("qgis:joinattributesbylocation",clipped_grid,source,['intersects'],0,0,"sum,mean,min,max,median",0,output)
34 |
35 |
36 | bears = QgsVectorLayer(output, "Bear Sightings", "ogr")
37 |
38 | # Label, expression, color, symbol alpha
39 | rules = (
40 | ('RARE', '"BEARS" <= 5', (227,26,28,255), .2),
41 | ('UNCOMMON', '"BEARS" > 5 AND "BEARS" <= 15', (227,26,28,255), .4),
42 | ('OCCASIONAL', '"BEARS" > 15 AND "BEARS" <= 50', (227,26,28,255), .6),
43 | ('FREQUENT', '"BEARS" > 50', (227,26,28,255), 1),
44 | )
45 |
46 | # create a new rule-based renderer
47 | sym_bears = QgsFillSymbolV2.createSimple({"outline_color":"white","outline_width":".26"})
48 | rend_bears = QgsRuleBasedRendererV2(sym_bears)
49 |
50 | # get the "root" rule
51 | root_rule = rend_bears.rootRule()
52 |
53 | for label, exp, color, alpha in rules:
54 | # create a clone (i.e. a copy) of the default rule
55 | rule = root_rule.children()[0].clone()
56 | # set the label, exp and color
57 | rule.setLabel(label)
58 | rule.setFilterExpression(exp)
59 | r,g,b,a = color
60 | rule.symbol().setColor(QColor(r,g,b,a))
61 | # set the transparency level
62 | rule.symbol().setAlpha(alpha)
63 | # append the rule to the list of rules
64 | root_rule.appendChild(rule)
65 |
66 | # delete the default rule
67 | root_rule.removeChildAt(0)
68 |
69 | # apply the rend_rails to the rails
70 | bears.setRendererV2(rend_bears)
71 |
72 | QgsMapLayerRegistry.instance().addMapLayer(bears)
73 |
74 |
75 |
--------------------------------------------------------------------------------
/Chapter09/B06246_09_08-geoio.py:
--------------------------------------------------------------------------------
1 | # Using the __geo_interface__ Protocol
2 |
3 | # Based on code by Nathan Woodrow and modified by Martin Laloux
4 | # http://nathanw.net/2013/06/25/adding-__geo_interface__-to-qgis-geometry-and-feature/
5 | # https://github.com/mlaloux/Python-geo_interface-applications/blob/master/QGIS_add_geo_interface.py
6 |
7 | import json
8 |
9 | def mapping_feature(feature):
10 | geom = feature.geometry()
11 | properties = {}
12 | fields = [field.name() for field in feature.fields()]
13 | properties = dict(zip(fields, feature.attributes()))
14 | return { 'type' : 'Feature',
15 | 'properties' : properties,
16 | 'geometry' : geom.__geo_interface__}
17 |
18 | def mapping_geometry(geometry):
19 | geo = geometry.exportToGeoJSON()
20 | return json.loads(geo)
21 |
22 | QgsFeature.__geo_interface__ = property(lambda self: mapping_feature(self))
23 | QgsGeometry.__geo_interface__ = property(lambda self: mapping_geometry(self))
24 |
25 | # f.__geo_interface__
26 |
27 |
--------------------------------------------------------------------------------
/Chapter09/B06246_09_09-output.py:
--------------------------------------------------------------------------------
1 | # Getting the output file names from processing algorithms
2 |
3 | import processing
4 |
5 | def proc_output(algorithm):
6 | for output in processing.Processing.getAlgorithm(algorithm).outputs:
7 | return output.name
8 |
9 | proc_output("grass7:r.aspect")
10 | # 'aspect'
11 |
12 | proc_output("qgis:joinattributesbylocation")
13 | # 'OUTPUT'
14 |
15 |
--------------------------------------------------------------------------------
/Chapter09/B06246_09_10-points.py:
--------------------------------------------------------------------------------
1 | # Generating Points along a Line
2 |
3 | # https://github.com/GeospatialPython/Learn/raw/master/path.zip
4 |
5 | import processing
6 |
7 | line = QgsVectorLayer("/qgis_data/shapes/path/path.shp", "Line", "ogr")
8 |
9 | QgsMapLayerRegistry.instance().addMapLayer(line)
10 |
11 | processing.runandload("grass7:v.to.points",line,"100",1,False,"435727.015026,458285.819185,5566442.32879,5591754.78979",-1,0.0001,0,None)
12 |
13 | processing.runandload("qgis:randompointsinextent","435727.015026,458285.819185,5566442.32879,5591754.78979",100,100,None)
14 |
15 |
--------------------------------------------------------------------------------
/Chapter09/B06246_09_11-exprlbl.py:
--------------------------------------------------------------------------------
1 | # Using Expression-Based Labels
2 |
3 | # https://github.com/GeospatialPython/Learn/raw/master/MS_UrbanAnC10.zip
4 |
5 | pth = "/qgis_data/ms/MS_UrbanAnC10.shp"
6 |
7 | lyr = QgsVectorLayer(pth, "Urban Areas", "ogr")
8 |
9 | palyr = QgsPalLayerSettings()
10 |
11 | palyr.readFromLayer(lyr)
12 |
13 | palyr.fieldName = 'CASE WHEN "POP" > 50000 THEN NAME10 END'
14 |
15 | palyr.isExpression = True
16 |
17 | palyr.enabled = True
18 |
19 | palyr.writeToLayer(lyr)
20 |
21 | QgsMapLayerRegistry.instance().addMapLayer(lyr)
22 |
--------------------------------------------------------------------------------
/Chapter09/B06246_09_12-forms.py:
--------------------------------------------------------------------------------
1 | # Creating Dynamic Forms in QGIS
2 |
3 | # https://github.com/GeospatialPython/Learn/raw/master/MS_UrbanAnC10.zip
4 |
5 | from PyQt4.QtCore import *
6 | from PyQt4.QtGui import *
7 |
8 | popFld = None
9 | dynamicDialog = None
10 |
11 | def dynamicForm(dialog,lyrId,featId):
12 | global dynamicDialog
13 | dynamicDialog = dialog
14 | global popFld
15 | popFld = dialog.findChild(QLineEdit,"POP")
16 | buttonBox = dialog.findChild(QDialogButtonBox,"buttonBox")
17 | # Disconnect the button box signal.
18 | buttonBox.accepted.disconnect(dynamicDialog.accept)
19 | # Create our own signals and connect them to the dialog.
20 | buttonBox.accepted.connect(validate)
21 | buttonBox.rejected.connect(dynamicDialog.reject)
22 |
23 | def validate():
24 | # Make sure that the population > 0.
25 | if not float(popFld.text()) > 0:
26 | msg = QMessageBox(f)
27 | msg.setText("Population must be greater than zero.")
28 | msg.exec_()
29 | else:
30 | # Return the form as accpeted to QGIS.
31 | dynamicDialog.accept()
--------------------------------------------------------------------------------
/Chapter09/B06246_09_13-lines.py:
--------------------------------------------------------------------------------
1 | # Calculate Length for all Selected Lines
2 |
3 | # https://github.com/GeospatialPython/Learn/raw/master/ms_rails_mstm.zip
4 |
5 | pth = "/qgis_data/ms/ms_rails_mstm.shp"
6 | lyr = QgsVectorLayer(pth, "Railroads", "ogr")
7 | total = 0
8 | for f in lyr.getFeatures():
9 | geom = f.geometry()
10 | total += geom.length()
11 |
12 | print "{0:.2f} total kilometers of rails.".format(total / 1000)
13 |
--------------------------------------------------------------------------------
/Chapter09/B06246_09_14-diffcrs.py:
--------------------------------------------------------------------------------
1 | # Using a different Status Bar CRS than the Map
2 |
3 | # https://github.com/GeospatialPython/Learn/raw/master/MSCities_Geo_Pts.zip
4 |
5 | # Ensure "On the fly projection" is enabled in Project settings
6 |
7 | pth = "/qgis_data/ms/MSCities_Geo_Pts.shp"
8 | lyr = QgsVectorLayer(pth, "Cities", "ogr")
9 | QgsMapLayerRegistry.instance().addMapLayer(lyr)
10 | iface.mapCanvas().setDestinationCrs(QgsCoordinateReferenceSystem("EPSG:3815"))
--------------------------------------------------------------------------------
/Chapter09/B06246_09_15-htmlbls.py:
--------------------------------------------------------------------------------
1 | # Creating HTML Map Tips in QGIS
2 |
3 | from qgis.utils import qgsfunction
4 | from qgis.core import QGis
5 | import urllib
6 | import os
7 |
8 | @qgsfunction(0, "Python")
9 | def googleStreetView(values, feature, parent):
10 | """
11 | Returns a path to a local Google Street View
12 | image for the feature
13 | """
14 | x,y = feature.geometry().asPoint()
15 | baseurl = "https://maps.googleapis.com/maps/api/streetview?"
16 | w = 150
17 | h = 150
18 | fov = 90
19 | heading = 235
20 | pitch = 10
21 | params = "size={w}x{h}&".format(w,h)
22 | params += "location={y},{x}&".format(y,x)
23 | params += "fov={}&heading={}&pitch={}".format(fov, heading, pitch)
24 | url = baseurl + params
25 | tmpdir = "/qgis_data/tmp/"
26 | img = tmpdir + str(feature.id()) + ".jpg"
27 | if not os.path.isfile(img):
28 | urllib.urlretrieve(url, img)
29 | uri = "file://" + img
30 | return uri
31 |
32 | pth = "/qgis_data/nyc/nyc_museums_geo.shp"
33 | lyr = QgsVectorLayer(pth, "New York City Museums", "ogr")
34 | lyr.setDisplayField('
')
35 |
36 | QgsMapLayerRegistry.instance().addMapLayer(lyr)
37 |
38 | # QgsExpression.unregisterFunction("googleStreetView")
--------------------------------------------------------------------------------
/Chapter09/B06246_09_16-osmpoi.py:
--------------------------------------------------------------------------------
1 | # Using OpenStreetMap Points of Interest in QGIS
2 |
3 | # Requires QuickOSM QGIS plugin
4 |
5 | # https://github.com/GeospatialPython/Learn/raw/master/MSCoast_geo.zip
6 |
7 | import processing
8 |
9 | lyr = QgsVectorLayer("/qgis_data/ms/MSCoast_geo.shp", "MS Coast", "ogr")
10 | ext = lyr.extent()
11 | w = ext.xMinimum()
12 | s = ext.yMinimum()
13 | e = ext.xMaximum()
14 | n = ext.yMaximum()
15 |
16 | bbox = "%s,%s,%s,%s".format(w,e,s,n)
17 |
18 | factory = processing.runalg("quickosm:queryfactory","tourism","",True,"",25)
19 |
20 | q = factory["OUTPUT_QUERY"]
21 |
22 | results = processing.runalg("quickosm:queryoverpassapiwithastring","http://overpass-api.de/api/",q,bbox,"",None)
23 |
24 | osm = results["OUTPUT_FILE"]
25 |
26 | poly = "/qgis_data/ms/tourism_poly.shp"
27 | multiline = "/qgis_data/ms/tourism_multil.shp"
28 | line = "/qgis_data/ms/tourism_lines.shp"
29 | points = "/qgis_data/ms/tourism_points.shp"
30 |
31 | processing.runalg("quickosm:ogrdefault",osm,"","","","",poly,multiline,line,points)
32 |
33 | tourism_points = QgsVectorLayer(points, "Points of Interest", "ogr")
34 |
35 | QgsMapLayerRegistry.instance().addMapLayers([tourism_points, lyr])
36 |
--------------------------------------------------------------------------------
/Chapter09/B06246_09_17-proxy.py:
--------------------------------------------------------------------------------
1 | # Changing the QGIS Web Proxy
2 |
3 | from qgis.core import *
4 | from PyQt4.QtCore import *
5 | from PyQt4.QtNetwork import QNetworkRequest, QNetworkProxy
6 |
7 | settings={"Proxy enabled": u'proxy/proxyEnabled', "Proxy Host ": u'proxy/proxyHost', "Proxy Port": u'proxy/proxyPort'}
8 |
9 | home={"Proxy enabled": True, "Proxy Host ": "localhost", "Proxy Port": 8888}
10 | office={"Proxy enabled": True, "Proxy Host ": "192.168.168.165", "Proxy Port": 8080}
11 | cafe={"Proxy enabled": False, "Proxy Host ": "192.168.168.107", "Proxy Port": 8080}
12 |
13 | current=home
14 |
15 | s = QSettings()
16 |
17 | for key, val in settings.iteritems():
18 | settings_key=key
19 | for key2, val2 in current.iteritems():
20 | if key2==settings_key:
21 | settings_val=val2
22 | current_setting = s.value(str(val).decode('unicode-escape'))
23 | s.setValue(unicode(str(val)), settings_val)
24 | s.sync()
25 |
26 | proxyEnabled = s.value("proxy/proxyEnabled", "")
27 | proxyType = s.value("proxy/proxyType", "" )
28 | proxyHost = s.value("proxy/proxyHost", "" )
29 | proxyPort = s.value("proxy/proxyPort", "" )
30 | proxyUser = s.value("proxy/proxyUser", "" )
31 | proxyPassword = s.value("proxy/proxyPassword", "" )
32 | proxy = QNetworkProxy()
33 | proxy.setType(QNetworkProxy.HttpProxy)
34 | proxy.setHostName(proxyHost)
35 | proxy.setPort(int(proxyPort))
36 | proxy.setUser(proxyUser)
37 | proxy.setPassword(proxyPassword)
38 | QNetworkProxy.setApplicationProxy(proxy)
39 | net_man=QgsNetworkAccessManager.instance()
40 | stringlist= ""
41 | net_man.setupDefaultProxyAndCache ()
42 | net_man.setFallbackProxyAndExcludes(proxy, stringlist)
43 |
--------------------------------------------------------------------------------
/Chapter09/B06246_09_18-sched.py:
--------------------------------------------------------------------------------
1 | # Running QGIS Scripts as scheduled tasks
2 |
3 | # https://github.com/GeospatialPython/Learn/raw/master/Mississippi.zip
4 |
5 | import urllib
6 | import datetime
7 | import pytz
8 | import tarfile
9 | import sys
10 | import os
11 | import time
12 | import schedule
13 |
14 | # Tell Python where you will get processing from
15 | sys.path.append('/Applications/QGIS.app/Contents/Resources/python')
16 | sys.path.append("/Applications/QGIS.app/Contents/Resources/python/plugins/")
17 |
18 | from qgis.core import *
19 | from PyQt4.QtGui import *
20 |
21 | def clip():
22 |
23 | # NOAA NEXRAD daily precip shapefile base URL
24 | url = "http://water.weather.gov/precip/p_download_new"
25 |
26 | # Get the current date
27 | c = pytz.timezone("US/Central")
28 | d = c.localize(datetime.datetime.today())
29 |
30 | # Convert the current date values to strings padded with zeros
31 | year, month, day = d.year, str(d.month).zfill(2), str(d.day).zfill(2)
32 |
33 | # Format the date values for the URL
34 | y_m_d = "{}/{}/{}".format(year, month, day)
35 |
36 | # Base filename for the download and shapefile
37 | base = "nws_precip_last60days_observed"
38 |
39 | # Date string for file names
40 | ymd = "{}{}{}".format(year, month, day)
41 |
42 | # Tar'd/zipped download name
43 | targz = "{}_shape_{}.tar.gz".format(base, ymd)
44 |
45 | # Full precipitation data download URL
46 | download = "{}/{}/{}".format(url, y_m_d, targz)
47 |
48 | if not os.path.isfile(targz):
49 | # Download the tar-zipped shapefile
50 | urllib.urlretrieve(download, targz)
51 |
52 | # Extract the shapefile
53 | with tarfile.open(targz, "r:gz") as tfile:
54 | tfile.extractall(".")
55 |
56 | # precipitation shapefile name
57 | shp = "{}_{}.shp".format(base, ymd)
58 | shx = "{}_{}.shx".format(base, ymd)
59 | prj = "{}_{}.prj".format(base, ymd)
60 | dbf = "{}_{}.dbf".format(base, ymd)
61 |
62 | # Shapefile to clip
63 | in_shp = os.path.join(os.getcwd(), shp)
64 |
65 | # Shapefile we will use to clip
66 | clip = "/qgis_data/ms/mississippi.shp"
67 |
68 | # Output clipped shapefile
69 | clipped = "/qgis_data/ms/60_day_rainfall_{}.shp".format(ymd)
70 |
71 | app = QgsApplication([],True)
72 | QgsApplication.setPrefixPath(r"/Applications/QGIS.app/Contents/Plugins", True)
73 | QgsApplication.initQgis()
74 |
75 | from processing.core.Processing import Processing
76 | from processing.tools import general
77 | Processing.initialize()
78 |
79 | # Clip the shapefile
80 | general.runalg("qgis:clip", in_shp, clip, clipped)
81 |
82 | if os.path.isfile(targz):
83 | os.remove(targz)
84 | os.remove(shp)
85 | os.remove(shx)
86 | os.remove(prj)
87 | os.remove(dbf)
88 |
89 | QgsApplication.exitQgis()
90 |
91 | schedule.every(30).seconds.do(clip)
92 | #schedule.every().day.at("16:00").do(clip)
93 |
94 | while True:
95 | schedule.run_pending()
96 | time.sleep(1)
--------------------------------------------------------------------------------
/Chapter09/B06246_09_19-3D.py:
--------------------------------------------------------------------------------
1 | # Visualizing Data in 3D with WebGL
2 |
3 | from PyQt4.QtCore import QSize
4 | from qgis.core import QgsCoordinateReferenceSystem, QgsCoordinateTransform, QgsPoint
5 | from Qgis2threejs.api import Exporter
6 |
7 | iface.mapCanvas().setCrsTransformEnabled(False)
8 | iface.mapCanvas().setMapUnits(0)
9 |
10 | demPth = "/qgis_data/rasters/dem.asc"
11 |
12 | hillshadePth = "/qgis_data/rasters/hillshade.tif"
13 |
14 | dem = QgsRasterLayer(demPth, "DEM")
15 | hillshade = QgsRasterLayer(hillshadePth, "Hillshade")
16 |
17 | algorithm = QgsContrastEnhancement.StretchToMinimumMaximum
18 | limits = QgsRaster.ContrastEnhancementMinMax
19 |
20 | dem.setContrastEnhancement(algorithm, limits)
21 |
22 | s = QgsRasterShader()
23 | c = QgsColorRampShader()
24 | c.setColorRampType(QgsColorRampShader.INTERPOLATED)
25 | i = []
26 | qri = QgsColorRampShader.ColorRampItem
27 | i.append(qri(356.334, QColor(63,159,152,255), '356.334'))
28 | i.append(qri(649.292, QColor(96,235,155,255), '649.292'))
29 | i.append(qri(942.25, QColor(100,246,174,255), '942.25'))
30 | i.append(qri(1235.21, QColor(248,251,155,255), '1235.21'))
31 | i.append(qri(1528.17, QColor(246,190,39,255), '1528.17'))
32 | i.append(qri(1821.13, QColor(242,155,39,255), '1821.13'))
33 | i.append(qri(2114.08, QColor(165,84,26,255), '2114.08'))
34 | i.append(qri(2300, QColor(236,119,83,255), '2300'))
35 | i.append(qri(2700, QColor(203,203,203,255), '2700'))
36 | c.setColorRampItemList(i)
37 | s.setRasterShaderFunction(c)
38 | ps = QgsSingleBandPseudoColorRenderer(dem.dataProvider(), 1, s)
39 | ps.setOpacity(0.5)
40 | dem.setRenderer(ps)
41 |
42 | QgsMapLayerRegistry.instance().addMapLayers([dem, hillshade])
43 |
44 | outputPath = "/qgis_data/3D/3d.html"
45 |
46 | props = {
47 | "DEM": {
48 | "checkBox_Clip": False,
49 | "checkBox_Frame": False,
50 | "checkBox_Shading": True,
51 | "checkBox_Sides": True,
52 | "checkBox_Surroundings": False,
53 | "checkBox_TransparentBackground": False,
54 | "comboBox_ClipLayer": None,
55 | "comboBox_DEMLayer": dem.id(),
56 | "comboBox_TextureSize": 100,
57 | "horizontalSlider_DEMSize": 2,
58 | "lineEdit_Color": "",
59 | "lineEdit_ImageFile": "",
60 | "lineEdit_centerX": "",
61 | "lineEdit_centerY": "",
62 | "lineEdit_rectHeight": "",
63 | "lineEdit_rectWidth": "",
64 | "radioButton_MapCanvas": True,
65 | "radioButton_Simple": True,
66 | "spinBox_Height": 4,
67 | "spinBox_Roughening": 4,
68 | "spinBox_Size": 5,
69 | "spinBox_demtransp": 0,
70 | "visible": True
71 | },
72 | "OutputFilename": outputPath,
73 | "PluginVersion": "1.4.2",
74 | "Template": "3DViewer(dat-gui).html"
75 | }
76 |
77 | e = Exporter(iface)
78 | e.settings.loadSettings(props)
79 | canvas = iface.mapCanvas()
80 | e.setMapSettings(canvas.mapSettings())
81 | e.export(outputPath, openBrowser=True)
82 |
83 |
84 |
--------------------------------------------------------------------------------
/Chapter09/B06246_09_20-globe.py:
--------------------------------------------------------------------------------
1 | # Visualizing Data on a globe
2 |
3 | # https://github.com/GeospatialPython/Learn/raw/master/ufo.zip
4 |
5 | from PyQt4.QtCore import *
6 | from PyQt4.QtGui import *
7 | from mmqgis import mmqgis_library as mmqgis
8 | import platform
9 | import os
10 |
11 | pth = "/qgis_data/continental-us.shp"
12 |
13 | lyrName = "continental-us"
14 |
15 | lyr = QgsVectorLayer(pth, lyrName, "ogr")
16 |
17 | QgsMapLayerRegistry.instance().addMapLayer(lyr, False)
18 |
19 | output = "/qgis_data/us.kml"
20 |
21 | nameAttr = "FIPS_CNTRY"
22 |
23 | desc = "{{CNTRY_NAME}}"
24 |
25 | mmqgis.mmqgis_kml_export(iface, lyrName, nameAttr, desc, True, output, False)
26 |
27 | qds = QDesktopServices()
28 | url = QUrl.fromLocalFile(output)
29 | qds.openUrl(url)
--------------------------------------------------------------------------------
/Chapter09/B06246_09_21-globe_proj.py:
--------------------------------------------------------------------------------
1 | # Make a globe-like azimuthal orthographic projection
2 |
3 | # https://github.com/GeospatialPython/Learn/raw/master/countries.zip
4 |
5 | import processing
6 |
7 | pth = "/qgis_data/countries.shp"
8 |
9 | clipped = "/qgis_data/clipped_countries.shp"
10 |
11 | warped = "/qgis_data/sphere.shp"
12 |
13 | x = 22
14 | y = 36
15 |
16 | processing.runalg("cliptohemisphere:clipavectorlayertothehemispherecentredonauserspecifiedpoint",pth,y,x,500,clipped, progress=None)
17 |
18 | processing.runandload("qgis:reprojectlayer",clipped,"EPSG:53032",warped)
--------------------------------------------------------------------------------
/Chapter09/B06246_09_22-animate.py:
--------------------------------------------------------------------------------
1 | # Animating a layer
2 |
3 | # https://github.com/GeospatialPython/Learn/raw/master/ufo.zip
4 |
5 | # https://github.com/GeospatialPython/Learn/raw/master/alien_invasion.zip
6 |
7 | from mmqgis import mmqgis_library as mmqgis
8 |
9 | ufo_shp = "/qgis_data/ufo/alien_invasion.shp"
10 | us_shp = "/qgis_data/ufo/continental-us.shp"
11 |
12 | ufo = QgsVectorLayer(ufo_shp, "UFOs", "ogr")
13 |
14 | us = QgsVectorLayer(us_shp, "US", "ogr")
15 |
16 | QgsMapLayerRegistry.instance().addMapLayers([ufo, us])
17 |
18 | mmqgis.mmqgis_animate_lines(iface, "UFOs", False, 50, "/qgis_data/ufo/video")
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2017 Packt
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | # QGIS-Python-Programming-Cookbook-Second-Edition
5 | This is the code repository of the book, [QGIS Python Programming Cookbook](https://www.packtpub.com/application-development/qgis-python-programming-cookbook-second-edition?utm_source=GitHub&utm_medium=repository&utm_campaign=9781787124837), Second Edition, published by Packt. It contains all the supporting project files necessary to work through the book from start to finish.
6 |
7 | ## About the Book
8 | QGIS is a desktop geographic information system that facilitates data viewing, editing, and analysis. Paired with the most efficient scripting language—Python, we can write effective scripts that extend the core functionality of QGIS.
9 |
10 | ## Instructions and Navigations
11 | All of the code is organized into folders. Each folder starts with a number followed by the application name. For example, Chapter02.
12 |
13 | The code will look like the following:
14 | ```
15 | import os
16 | os.getcwd()
17 |
18 | ```
19 |
20 | With the following software and hardware list you can run all code files present in the book (Chapter 1-9)
21 |
22 | ### Software and Hardware List
23 |
24 | | Chapter | Software required | OS required |
25 | | -------- | ------------------------------------| ---------------------------------------|
26 | | 1-9 |QGIS 2.18 | Windows, Mac OS X, BSD and Linux (Any) |
27 | | 1 |IBM Java 8 Dev kit | Windows, Mac OS X, BSD and Linux (Any) |
28 | | 1 |IBM Eclipse Neon 4.6.0 | Windows, Mac OS X, BSD and Linux (Any) |
29 | | 9 |Google Earth | Windows, Mac OS X, BSD and Linux (Any) |
30 |
31 |
32 | ## Related Products
33 | * [Programming ArcGIS with Python Cookbook - Second Edition](https://www.packtpub.com/application-development/programming-arcgis-python-cookbook-second-edition?utm_source=GitHub&utm_medium=repository&utm_campaign=9781785282898)
34 |
35 | * [Raspberry Pi for Python Programmers Cookbook - Second Edition](https://www.packtpub.com/hardware-and-creative/raspberry-pi-python-programmers-cookbook-second-edition?utm_source=GitHub&utm_medium=repository&utm_campaign=9781785288326)
36 |
37 |
38 | ### Suggestions and Feedback
39 | [Click here](https://docs.google.com/forms/d/e/1FAIpQLSe5qwunkGf6PUvzPirPDtuy1Du5Rlzew23UBp2S-P3wB-GcwQ/viewform) if you have any feedback or suggestions.
40 |
41 | ### Download a free PDF
42 |
43 | If you have already purchased a print or Kindle version of this book, you can get a DRM-free PDF version at no cost.
Simply click on the link to claim your free PDF.
44 | https://packt.link/free-ebook/9781787124837
--------------------------------------------------------------------------------