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

Consuming pgRouting functionality in a web app

A final example of our pgRouting journey is a web application that consumes some of the functionality we have seen so far.

In order to preview the example, navigate to the example's folder - apps/pgrouting, run sencha app watch, and navigate to http://localhost:1841/apps/pgrouting/. You should see a similar output (you will have to calculate a route and drive time zone first though):

In order to feed our web app, we need to prepare a web service first. We have gone through creating a nice REST-like API for our WebGIS examples in the previous chapter, so this time all the maintenance stuff is going to be omitted.

At this stage, I assume our barebones web server is up and running, so we just need to plug in some functionality.

In order to perform any routing related logic, we should have the IDs of the vertices we would like to use in our analysis. Let's start with a function that snaps the clicked Lon/Lat to the nearest vertex in our network:

router.route('/snaptonetwork').get((req, res) => { 

//init client with the appropriate conn details
let client = new pg.Client(dbCredentials);

client.connect((err) => {
if(err){
sendErrorResponse(res, 'Error connecting to the database: ' + err.message);
return;
}

let query =
`SELECT
id, lon, lat
FROM
pgr.ways_vertices_pgr
ORDER BY
ST_Distance(
ST_GeomFromText('POINT(' || $1 || ' ' || $2 ||' )',4326),
the_geom
)
LIMIT 1;`;

//once connected we can now interact with a db
client.query(query, [req.query.lon, req.query.lat], (err, result) =>{

//close the connection when done
client.end();

if(err){
sendErrorResponse(res, 'Error snapping node: ' + err.message);
return;
}

res.statusCode = 200;

res.json({
query: query,
node: result.rows[0]
});
});
});
});

The preceding method takes in a pair of coordinates expressing latitude and longitude and snaps them to the nearest vertex found in the network. It returns the ID of the node with its coordinates, as well as the query executed, so it is possible to see how our database is queried.

This API is used every time a map is clicked, in order to provide an input point for further processing.

In the map client, one can use buttons with green and red pins to define start and end route points, respectively. Once this is done, a button with the map directions sign symbol triggers another API method call - the one that calculates the route. It takes in the IDs of nodes to calculate the shortest path between them:

let query =  
`select
ST_AsText(
ST_LineMerge(
ST_Union(ways.the_geom)
)
) as wkt
from
(
select
*
from
pgr_dijkstra(
'select gid as id, source, target, length_m as cost from pgr.ways',
$1::int4, $2::int4
)
) as route
left outer join pgr.ways ways on ways.gid = route.edge;`;
Since most of our API methods body is pretty much the same, only the actual SQL executed is presented.

We have seen a similar query already, when explaining how to get from a list of coordinates and edges output by the Dijkstra algorithm to the actual geometries representing the edges.

The preceding version does a few more operations - it unions the separate LineString edges into a MultiLineString geometry, then joins the MultiLineString into a single LineString to finally encode it as a WKT geometry, so our client app can handle it.

Because we use the minimal signature of the Dijkstra algorithm, it assumes the graph is directed, and this can be seen when our start point snaps to the edge of a dual carriage way and the general direction of a route is backwards:

We have a final method to implement in our pgRouting API - we need to calculate drive time zones. In this scenario, we take in a node ID and the driving time in seconds and output a polygon representing an alpha shape:

let query =  
`select ST_AsText(
pgr_pointsAsPolygon(
'select
v.id::int4, v.lon::float8 as x, v.lat::float8 as y
from(
select * from pgr_drivingDistance(''''select gid as id, source, target, cost_s as cost from pgr.ways'''', ' || $1 || ',' || $2 || ')
) as dd
left outer join pgr.ways_vertices_pgr v on dd.node = v.id'
)
) as wkt;`;

Once again, we have seen a similar query already; the difference is encoding the geometry as wkt.

The client side is rather simple and is pretty much about declaring the UI with some basic interactions, a map with the OSM base layer, and two vector layers with some customized styling. API calls use standard AJAX requests and then, on success, the executed query is displayed in the right-hand side panel and, also, the returned WKT is parsed and displayed on the map. Nothing fancy really.

It is worth noticing though, that the map projection in this example is EPSG:3857 and the network data is in EPSG:4326. So the geometries need to be re-projected before being sent out to the API and, when the WKT geometry is retrieved, it needs to be displayed on a map.

The full source code of this example can be found in this chapter's resources, so you may study it in detail as needed.