Table of Contents for
Mastering PostGIS

Version ebook / Retour

Cover image for bash Cookbook, 2nd Edition Mastering PostGIS by Tomasz Nycz Published by Packt Publishing, 2017
  1. Mastering PostGIS
  2. Title Page
  3. Copyright
  4. Credits
  5. About the Authors
  6. About the Reviewers
  7. www.PacktPub.com
  8. Customer Feedback
  9. Table of Contents
  10. Preface
  11. What this book covers
  12. What you need for this book
  13. Who this book is for
  14. Conventions
  15. Reader feedback
  16. Customer support
  17. Downloading the example code
  18. Downloading the color images of this book
  19. Errata
  20. Piracy
  21. Questions
  22. Importing Spatial Data
  23. Obtaining test data
  24. Setting up the database
  25. Importing flat data
  26. Importing data using psql
  27. Importing data interactively
  28. Importing data non-interactively
  29. Importing data using pgAdmin
  30. Extracting spatial information from flat data
  31. Importing shape files using shp2pgsql
  32. shp2pgsql in cmd
  33. The shp2pgsql GUI version
  34. Importing vector data using ogr2ogr
  35. Importing GML
  36. Importing MIF and TAB
  37. Importing KML
  38. ogr2ogr GUI (Windows only)
  39. Importing data using GIS clients
  40. Exporting a shapefile to PostGIS using QGIS and SPIT
  41. Exporting shapefile to PostGIS using QGIS and DbManager
  42. Exporting spatial data to PostGIS from Manifold GIS
  43. Importing OpenStreetMap data
  44. Connecting to external data sources with foreign data wrappers
  45. Connecting to SQL Server Spatial
  46. Connecting to WFS service
  47. Loading rasters using raster2pgsql
  48. Importing a single raster
  49. Importing multiple rasters
  50. Importing data with pgrestore
  51. Summary
  52. Spatial Data Analysis
  53. Composing and decomposing geometries
  54. Creating points
  55. Extracting coordinates from points
  56. Composing and decomposing Multi-geometries
  57. Multi-geometry decomposition
  58. Composing and decomposing LineStrings
  59. LineString composition
  60. LineString decomposition
  61. Composing and decomposing polygons
  62. Polygon composition
  63. Polygon decomposition
  64. Spatial measurement
  65. General warning - mind the SRID!
  66. Measuring distances between two geometries
  67. Measuring the length, area, and perimeter of geometries
  68. Line length
  69. Polygon perimeter
  70. Polygon area
  71. Geometry bounding boxes
  72. Accessing bounding boxes
  73. Creating bounding boxes
  74. Using bounding boxes in spatial queries
  75. Geometry simplification
  76. Geometry validation
  77. Simplicity and validity
  78. Testing for simplicity and validity
  79. Checking for validity
  80. Repairing geometry errors
  81. Validity constraint
  82. Intersecting geometries
  83. Nearest feature queries
  84. Summary
  85. Data Processing - Vector Ops
  86. Primer - obtaining and importing OpenStreetMap data
  87. Merging geometries
  88. Merging polygons
  89. Merging MultiLineStrings
  90. Slicing geometries
  91. Splitting a polygon by LineString
  92. Splitting a LineString with another LineString
  93. Extracting a section of LineString
  94. Buffering and offsetting geometries
  95. Offsetting features
  96. Creating convex and concave hulls
  97. Computing centroids, points-on-surface, and points-on-line
  98. Reprojecting geometries
  99. Spatial relationships
  100. Touching
  101. Crossing
  102. Overlapping
  103. Containing
  104. Radius queries
  105. Summary
  106. Data Processing - Raster Ops
  107. Preparing data
  108. Processing and analysis
  109. Analytic and statistical functions
  110. Vector to raster conversion
  111. Raster to vector conversion
  112. Spatial relationship
  113. Metadata
  114. Summary
  115. Exporting Spatial Data
  116. Exporting data using \COPY in psql
  117. Exporting data in psql interactively
  118. Exporting data in psql non-interactively
  119. Exporting data in PgAdmin
  120. Exporting vector data using pgsql2shp
  121. pgsql2sph command line
  122. pgsql2shp gui
  123. Exporting vector data using ogr2ogr
  124. Exporting KML revisited
  125. Exporting SHP
  126. Exporting MapInfo TAB and MIF
  127. Exporting to SQL Server
  128. ogr2ogr GUI
  129. Exporting data using GIS clients
  130. Exporting data using QGIS
  131. Exporting data using Manifold.
  132. Outputting rasters using GDAL
  133. Outputting raster using psql
  134. Exporting data using the PostgreSQL backup functionality
  135. Summary
  136. ETL Using Node.js
  137. Setting up Node.js
  138. Making a simple Node.js hello world in the command line
  139. Making a simple HTTP server
  140. Handshaking with a database using Node.js PgSQL client
  141. Retrieving and processing JSON data
  142. Importing shapefiles revisited
  143. Consuming JSON data
  144. Geocoding address data
  145. Consuming WFS data
  146. Summary
  147. PostGIS – Creating Simple WebGIS Applications
  148. ExtJS says Hello World
  149. Configuring GeoServer web services
  150. Importing test data
  151. Outputting vector data as WMS services in GeoServer
  152. Outputting raster data as WMS services in GeoServer
  153. Outputting vector data as WFS services
  154. Making use of PgRaster in a simple WMS GetMap handler
  155. Consuming WMS
  156. Consuming WMS in ol3
  157. Consuming WMS in Leaflet
  158. Enabling CORS in Jetty
  159. Consuming WFS in ol3
  160. Outputting and consuming GeoJSON
  161. Consuming GeoJSON in ol3
  162. Consuming GeoJSON in Leaflet
  163. Outputting and consuming TopoJSON
  164. Consuming TopoJSON in ol3
  165. Consuming TopoJSON in Leaflet
  166. Implementing a simple CRUD application that demonstrates vector editing via web interfaces
  167. WebGIS CRUD server in Node.js
  168. WebGIS CRUD client
  169. Layer manager
  170. Drawing tools
  171. Analysis tools - buffering
  172. Summary
  173. PostGIS Topology
  174. The conceptual model
  175. The data
  176. Installation
  177. Creating an empty topology
  178. Importing Simple Feature data into topology
  179. Checking the validity of input geometries
  180. Creating a TopoGeometry column and a topology layer
  181. Populating a TopoGeometry column from an existing geometry
  182. Inspecting and validating a topology
  183. Topology validation
  184. Accessing the topology data
  185. Querying topological elements by a point
  186. Locating nodes
  187. Locating edges
  188. Locating faces
  189. Topology editing
  190. Adding new elements
  191. Creating TopoGeometries
  192. Splitting and merging features
  193. Splitting features
  194. Merging features
  195. Updating edge geometry
  196. Topology-aware simplification
  197. Importing sample data
  198. Topology output
  199. GML output
  200. TopoJSON output
  201. Summary
  202. pgRouting
  203. Installing the pgRouting extension
  204. Importing routing data
  205. Importing shapefiles
  206. Importing OSM data using osm2pgrouting
  207. pgRouting algorithms
  208. All pairs shortest path
  209. Shortest path
  210. Shortest path Dijkstra
  211. A-Star (A*)
  212. K-Dijkstra
  213. K-Shortest path
  214. Turn restrictions shortest path (TRSP)
  215. Driving distance
  216. Traveling sales person
  217. Handling one-way edges
  218. Consuming pgRouting functionality in a web app
  219. Summary

Importing shapefiles

In this example, we will use an example of a routable shapefile downloaded from GeoFabrik.de - https://www.geofabrik.de/data/shapefiles_routable_vienna.zip. A routable shapefile, as GeoFabrik describes it, is a standard shapefile that contains OSM data preprocessed with routing in mind. This means it contains only road data with lines split at intersections, with some speed limits information, road line lengths, and so on.

We have already addressed importing shapefiles to PostGIS, so you can use a tool of your choice; in this case, I am using osm2pgsql:

shp2pgsql -s 4326 roads pgr.shp_roads | psql -h localhost -p 5434 -U postgres -d mastering_postgis 

Once our vector makes it to the database, we need to do some further processing before it is possible to issue pgRouting-specific queries against the dataset.

pgRouting requires the network edges (road lines) to be LineStrings. You may have noticed that shp2pgsql imported our lines as MultiLineStrings, but let's verify this:

select distinct st_GeometryType(geom) from pgr.shp_roads; 

The result should be ST MulitLineString and we have to fix that.

shp2pgsql does offer a -S param to create simple geometries instead of the default multi geometries. Unfortunately, our dataset of choice does contain multi geoms so we have to approach it differently.

In order to turn the MultiLineStrings into LineStrings (and split them when required) a ST_Dump function will come in handy. Basically, it extracts the geometry paths off a MultiGeometry:

select 
gid, osm_id, code, fclass, name, ref, oneway, maxspeed, layer, ete, speed, length, bridge, tunnel,
(ST_Dump(geom)).geom as geom
into pgr.shp_roads_fixed
from
pgr.shp_roads;

Let's verify our fixed data - this time, the expected output is ST LineString:

select distinct st_GeometryType(geom) from pgr.shp_roads_fixed; 

pgRouting works with its own specific flavor of topology, so we need to create pgRouting topology for our data. We will use a pgr_CreateTopology function to prepare the data. It requires two extra columns in the roads dataset, both integers - one for the start point identifier and the other one for the endpoint identifier; their default names are source and target, respectively. Let's modify our roads data model to cater for the requirements:

ALTER TABLE pgr.shp_roads_fixed ADD COLUMN source integer; 
ALTER TABLE pgr.shp_roads_fixed ADD COLUMN target integer;

At this stage, we should be able to create the pgRouting topology. So, let's do just that:

select pgr_createTopology( 
'pgr.shp_roads_fixed', --edge_table; network table name
0.000001, --tolerance; snapping tolerance with disconnected edges
'geom', --name of the geometry column in the network table
'gid', --name of the identifier column in the network table
'source', --name of the source identifier column in the network table
'target' --name of the target identifier column in the network table
--rows_where: condition to select a subset of records; defaults to true to process all the rows where the source / target are nulls; otherwise the subset of rows is processed
--clean: boolean - clean any previous topology; defaults to false
);

In the preceding code, I included the explanation of each parameter. Basically, this code creates pgRouting topology for our roads dataset. The roads table gets modified - source and target columns are filled with new data; indexes are created for ID, geom, source, and target columns.

If the topology has been created, you should see an OK result; FAIL otherwise. If the operation failed and you happen to use pgAdmin to run queries, review the Messages tab for details on what the reason for the failure.

You should notice that a new table has been created: shp_roads_fixed_vertices_pgr.

We can now verify the graph by using the pgr_analyzeGraph function:

select pgr_analyzeGraph('pgr.shp_roads_fixed', 0.00001, 'geom', 'gid'); 

It will also show either OK or FAIL, but when you look at the notifications (if you run the command via psql, you will see the output in the CMD; in pgAdmin you will need to switch to the Messages tab) you should see a similar output:

NOTICE:  Performing checks, please wait ...
NOTICE: Analyzing for dead ends. Please wait...
NOTICE: Analyzing for gaps. Please wait...
NOTICE: Analyzing for isolated edges. Please wait...
NOTICE: Analyzing for ring geometries. Please wait...
NOTICE: Analyzing for intersections. Please wait...
NOTICE: ANALYSIS RESULTS FOR SELECTED EDGES:
NOTICE: Isolated segments: 59
NOTICE: Dead ends: 7534
NOTICE: Potential gaps found near dead ends: 17
NOTICE: Intersections detected: 1064
NOTICE: Ring geometries: 220
pgr_analyzegraph
------------------
OK
(1 row)

Dead ends and potential gap problems are also identified in the vertices table in the cnt and chk columns:

select  
(select count(*) FROM pgr.shp_roads_fixed_vertices_pgr WHERE cnt = 1) as deadends,
(select count(*) FROM pgr.shp_roads_fixed_vertices_pgr WHERE chk = 1) as gaps