Table of Contents for
PostGIS Cookbook - Second Edition

Version ebook / Retour

Cover image for bash Cookbook, 2nd Edition PostGIS Cookbook - Second Edition by Thomas J Kraft Published by Packt Publishing, 2018
  1. PostGIS Cookbook, Second Edition
  2. Title Page
  3. Copyright and Credits
  4. PostGIS Cookbook Second Edition
  5. Packt Upsell
  6. Why subscribe?
  7. PacktPub.com
  8. Contributors
  9. About the authors
  10. Packt is searching for authors like you
  11. Table of Contents
  12. Preface
  13. Who this book is for
  14. What this book covers
  15. To get the most out of this book
  16. Download the example code files
  17. Download the color images
  18. Conventions used
  19. Sections
  20. Getting ready
  21. How to do it…
  22. How it works…
  23. There's more…
  24. See also
  25. Get in touch
  26. Reviews
  27. Moving Data In and Out of PostGIS
  28. Introduction
  29. Importing nonspatial tabular data (CSV) using PostGIS functions
  30. Getting ready
  31. How to do it...
  32. How it works...
  33. Importing nonspatial tabular data (CSV) using GDAL
  34. Getting ready
  35. How to do it...
  36. How it works...
  37. Importing shapefiles with shp2pgsql
  38. How to do it...
  39. How it works...
  40. There's more...
  41. Importing and exporting data with the ogr2ogr GDAL command
  42. How to do it...
  43. How it works...
  44. See also
  45. Handling batch importing and exporting of datasets
  46. Getting ready
  47. How to do it...
  48. How it works...
  49. Exporting data to a shapefile with the pgsql2shp PostGIS command
  50. How to do it...
  51. How it works...
  52. Importing OpenStreetMap data with the osm2pgsql command
  53. Getting ready
  54. How to do it...
  55. How it works...
  56. Importing raster data with the raster2pgsql PostGIS command
  57. Getting ready
  58. How to do it...
  59. How it works...
  60. Importing multiple rasters at a time
  61. Getting ready
  62. How to do it...
  63. How it works...
  64. Exporting rasters with the gdal_translate and gdalwarp GDAL commands
  65. Getting ready
  66. How to do it...
  67. How it works...
  68. See also
  69. Structures That Work
  70. Introduction
  71. Using geospatial views
  72. Getting ready
  73. How to do it...
  74. How it works...
  75. There's more...
  76. See also
  77. Using triggers to populate the geometry column
  78. Getting ready
  79. How to do it...
  80. There's more...
  81. Extending further...
  82. See also
  83. Structuring spatial data with table inheritance
  84. Getting ready
  85. How to do it...
  86. How it works...
  87. See also
  88. Extending inheritance – table partitioning
  89. Getting ready
  90. How to do it...
  91. How it works...
  92. See also
  93. Normalizing imports
  94. Getting ready
  95. How to do it...
  96. How it works...
  97. There's more...
  98. Normalizing internal overlays
  99. Getting ready
  100. How to do it...
  101. How it works...
  102. There's more...
  103. Using polygon overlays for proportional census estimates
  104. Getting ready
  105. How to do it...
  106. How it works...
  107. Working with Vector Data – The Basics
  108. Introduction
  109. Working with GPS data
  110. Getting ready
  111. How to do it...
  112. How it works...
  113. Fixing invalid geometries
  114. Getting ready
  115. How to do it...
  116. How it works...
  117. GIS analysis with spatial joins
  118. Getting ready
  119. How to do it...
  120. How it works...
  121. Simplifying geometries
  122. How to do it...
  123. How it works...
  124. Measuring distances
  125. Getting ready
  126. How to do it...
  127. How it works...
  128. Merging polygons using a common attribute
  129. Getting ready
  130. How to do it...
  131. How it works...
  132. Computing intersections
  133. Getting ready
  134. How to do it...
  135. How it works...
  136. Clipping geometries to deploy data
  137. Getting ready
  138. How to do it...
  139. How it works...
  140. Simplifying geometries with PostGIS topology
  141. Getting ready
  142. How to do it...
  143. How it works...
  144. Working with Vector Data – Advanced Recipes
  145. Introduction
  146. Improving proximity filtering with KNN
  147. Getting ready
  148. How to do it...
  149. How it works...
  150. See also
  151. Improving proximity filtering with KNN – advanced
  152. Getting ready
  153. How to do it...
  154. How it works...
  155. See also
  156. Rotating geometries
  157. Getting ready
  158. How to do it...
  159. How it works...
  160. See also
  161. Improving ST_Polygonize
  162. Getting ready
  163. How to do it...
  164. See also
  165. Translating, scaling, and rotating geometries – advanced
  166. Getting ready
  167. How to do it...
  168. How it works...
  169. See also
  170. Detailed building footprints from LiDAR
  171. Getting ready
  172. How to do it...
  173. How it works...
  174. Creating a fixed number of clusters from a set of points
  175. Getting ready
  176. How to do it...
  177. Calculating Voronoi diagrams
  178. Getting ready
  179. How to do it...
  180. Working with Raster Data
  181. Introduction
  182. Getting and loading rasters
  183. Getting ready
  184. How to do it...
  185. How it works...
  186. Working with basic raster information and analysis
  187. Getting ready
  188. How to do it...
  189. How it works...
  190. Performing simple map-algebra operations
  191. Getting ready
  192. How to do it...
  193. How it works...
  194. Combining geometries with rasters for analysis
  195. Getting ready
  196. How to do it...
  197. How it works...
  198. Converting between rasters and geometries
  199. Getting ready
  200. How to do it...
  201. How it works...
  202. Processing and loading rasters with GDAL VRT
  203. Getting ready
  204. How to do it...
  205. How it works...
  206. Warping and resampling rasters
  207. Getting ready
  208. How to do it...
  209. How it works...
  210. Performing advanced map-algebra operations
  211. Getting ready
  212. How to do it...
  213. How it works...
  214. Executing DEM operations
  215. Getting ready
  216. How to do it...
  217. How it works...
  218. Sharing and visualizing rasters through SQL
  219. Getting ready
  220. How to do it...
  221. How it works...
  222. Working with pgRouting
  223. Introduction
  224. Startup – Dijkstra routing
  225. Getting ready
  226. How to do it...
  227. Loading data from OpenStreetMap and finding the shortest path using A*
  228. Getting ready
  229. How to do it...
  230. How it works...
  231. Calculating the driving distance/service area
  232. Getting ready
  233. How to do it...
  234. See also
  235. Calculating the driving distance with demographics
  236. Getting ready
  237. How to do it...
  238. Extracting the centerlines of polygons
  239. Getting ready
  240. How to do it...
  241. There's more...
  242. Into the Nth Dimension
  243. Introduction
  244. Importing LiDAR data
  245. Getting ready
  246. How to do it...
  247. See also
  248. Performing 3D queries on a LiDAR point cloud
  249. How to do it...
  250. Constructing and serving buildings 2.5D
  251. Getting ready
  252. How to do it...
  253. Using ST_Extrude to extrude building footprints
  254. How to do it...
  255. Creating arbitrary 3D objects for PostGIS
  256. Getting ready
  257. How to do it...
  258. Exporting models as X3D for the web
  259. Getting ready
  260. How to do it...
  261. There's more...
  262. Reconstructing Unmanned Aerial Vehicle (UAV) image footprints with PostGIS 3D
  263. Getting started
  264. How to do it...
  265. UAV photogrammetry in PostGIS – point cloud
  266. Getting ready
  267. How to do it...
  268. UAV photogrammetry in PostGIS – DSM creation
  269. Getting ready
  270. How to do it...
  271. PostGIS Programming
  272. Introduction
  273. Writing PostGIS vector data with Psycopg
  274. Getting ready
  275. How to do it...
  276. How it works...
  277. Writing PostGIS vector data with OGR Python bindings
  278. Getting ready
  279. How to do it...
  280. How it works...
  281. Writing PostGIS functions with PL/Python
  282. Getting ready
  283. How to do it...
  284. How it works...
  285. Geocoding and reverse geocoding using the GeoNames datasets
  286. Getting ready
  287. How to do it...
  288. How it works...
  289. Geocoding using the OSM datasets with trigrams
  290. Getting ready
  291. How to do it...
  292. How it works...
  293. Geocoding with geopy and PL/Python
  294. Getting ready
  295. How to do it...
  296. How it works...
  297. Importing NetCDF datasets with Python and GDAL
  298. Getting ready
  299. How to do it...
  300. How it works...
  301. PostGIS and the Web
  302. Introduction
  303. Creating WMS and WFS services with MapServer
  304. Getting ready
  305. How to do it...
  306. How it works...
  307. See also
  308. Creating WMS and WFS services with GeoServer
  309. Getting ready
  310. How to do it...
  311. How it works...
  312. See also
  313. Creating a WMS Time service with MapServer
  314. Getting ready
  315. How to do it...
  316. How it works...
  317. Consuming WMS services with OpenLayers
  318. Getting ready
  319. How to do it...
  320. How it works..
  321. Consuming WMS services with Leaflet
  322. How to do it...
  323. How it works...
  324. Consuming WFS-T services with OpenLayers
  325. Getting ready
  326. How to do it...
  327. How it works...
  328. Developing web applications with GeoDjango – part 1
  329. Getting ready
  330. How to do it...
  331. How it works...
  332. Developing web applications with GeoDjango – part 2
  333. Getting ready
  334. How to do it...
  335. How it works...
  336. Developing a web GPX viewer with Mapbox
  337. How to do it...
  338. How it works...
  339. Maintenance, Optimization, and Performance Tuning
  340. Introduction
  341. Organizing the database
  342. Getting ready
  343. How to do it...
  344. How it works...
  345. Setting up the correct data privilege mechanism
  346. Getting ready
  347. How to do it...
  348. How it works...
  349. Backing up the database
  350. Getting ready
  351. How to do it...
  352. How it works...
  353. Using indexes
  354. Getting ready
  355. How to do it...
  356. How it works...
  357. Clustering for efficiency
  358. Getting ready
  359. How to do it...
  360. How it works...
  361. Optimizing SQL queries
  362. Getting ready
  363. How to do it...
  364. How it works...
  365. Migrating a PostGIS database to a different server
  366. Getting ready
  367. How to do it...
  368. How it works...
  369. Replicating a PostGIS database with streaming replication
  370. Getting ready
  371. How to do it...
  372. How it works...
  373. Geospatial sharding
  374. Getting ready
  375. How to do it...
  376. How it works...
  377. Paralellizing in PosgtreSQL
  378. Getting ready
  379. How to do it...
  380. How it works...
  381. Using Desktop Clients
  382. Introduction
  383. Adding PostGIS layers – QGIS
  384. Getting ready
  385. How to do it...
  386. How it works...
  387. Using the Database Manager plugin – QGIS
  388. Getting ready
  389. How to do it...
  390. How it works...
  391. Adding PostGIS layers – OpenJUMP GIS
  392. Getting ready
  393. How to do it...
  394. How it works...
  395. Running database queries – OpenJUMP GIS
  396. Getting ready
  397. How to do it...
  398. How it works...
  399. Adding PostGIS layers – gvSIG
  400. Getting ready
  401. How to do it...
  402. How it works...
  403. Adding PostGIS layers – uDig
  404. How to do it...
  405. How it works...
  406. Introduction to Location Privacy Protection Mechanisms
  407. Introduction
  408. Definition of Location Privacy Protection Mechanisms – LPPMs
  409. Classifying LPPMs
  410. Adding noise to protect location data
  411. Getting ready
  412. How to do it...
  413. How it works...
  414. Creating redundancy in geographical query results
  415. Getting ready
  416. How to do it...
  417. How it works...
  418. References
  419. Other Books You May Enjoy
  420. Leave a review - let other readers know what you think

How to do it...

Carry out the following steps:

  1. Create a Django project using the django-admin command with the startproject option. Name the project wildlife. The command for creating the project will be as follows:
      (chp09-env)$ cd ~/postgis_cookbook/working/chp09
      (chp09-env)$ django-admin.py startproject wildlife
  1. Create a Django application using the django-admin command with the startapp option. Name the application sightings. The command will be as follows:
      (chp09-env)$ cd wildlife/
      (chp09-env)$ django-admin.py startapp sightings

Now you should have the following directory structure:

  1. You will need to edit some files. Open your favorite editor (Sublime Text does the job) and go to the settings in the settings.py file in the code bundle under chp09/wildlife/wildlife. First, the DATABASES settings should be as shown in the following code, in order to use the postgis_cookbook PostGIS database for your application data:
        DATABASES = { 
          'default': { 
            'ENGINE': 'django.contrib.gis.db.backends.postgis', 
            'NAME': 'postgis_cookbook', 
            'USER': 'me', 
            'PASSWORD': 'mypassword', 
            'HOST': 'localhost', 
            'PORT': '', 
          } 
        } 
  1. Add the following two lines of code at the top of the wildlife/settings.py file (PROJECT_PATH is the variable in which you will enter the project's path in the settings menu):
        import os 
        PROJECT_PATH = os.path.abspath(os.path.dirname(__file__)) 
  1. Make sure that in the settings.py file under chp09/wildlife/wildlife, MEDIA_ROOT, and MEDIA_URL are correctly set, as shown the following code (this is to set the media files' path and URLs for the images that the administrative user will upload):
        MEDIA_ROOT = os.path.join(PROJECT_PATH, "media") 
        MEDIA_URL = '/media/'
  1. Make sure that the INSTALLED_APPS setting looks as shown in the following code in the settings.py file. You will use the Django admin site (django.contrib.admin), the GeoDjango core library (django.contrib.gis), and the sightings application you are creating in this recipe and the next. For this purpose, add the last three lines:
        INSTALLED_APPS = ( 
          'django.contrib.admin', 
          'django.contrib.auth', 
          'django.contrib.contenttypes', 
          'django.contrib.sessions', 
          'django.contrib.messages', 
          'django.contrib.staticfiles', 
          'django.contrib.gis', 
          'sightings', 
        ) 
  1. Now, synchronize the database using the Django migrations management commands. When prompted to create a superuser, answer yes and choose a preferred administrative username and password:
      (chp09-env)$ python manage.py makemigrations
      (chp09-env)$ python manage.py migrate
  1. Now you will add the models needed by the application. Edit the models.py file under chp09/wildlife/sightings and add the following code:
        from django.db import models 
        from django.contrib.gis.db import models as gismodels 
 
        class Country(gismodels.Model): 
          """ 
            Model to represent countries. 
          """ 
          isocode = gismodels.CharField(max_length=2) 
          name = gismodels.CharField(max_length=255) 
          geometry = gismodels.MultiPolygonField(srid=4326) 
          objects = gismodels.GeoManager() 
 
          def __unicode__(self): 
            return '%s' % (self.name) 
 
        class Animal(models.Model): 
          """ 
            Model to represent animals. 
          """ 
          name = models.CharField(max_length=255) 
          image = models.ImageField(upload_to='animals.images') 
 
          def __unicode__(self): 
            return '%s' % (self.name) 
 
          def image_url(self): 
            return u'<img src="%s" alt="%s" width="80"></img>' % 
(self.image.url, self.name) image_url.allow_tags = True class Meta: ordering = ['name'] class Sighting(gismodels.Model): """ Model to represent sightings. """ RATE_CHOICES = ( (1, '*'), (2, '**'), (3, '***'), ) date = gismodels.DateTimeField() description = gismodels.TextField() rate = gismodels.IntegerField(choices=RATE_CHOICES) animal = gismodels.ForeignKey(Animal) geometry = gismodels.PointField(srid=4326) objects = gismodels.GeoManager() def __unicode__(self): return '%s' % (self.date) class Meta: ordering = ['date']
  1. Each model will become a table in the database with the corresponding fields defined using the models and gismodels class. Note that the geometry variable in the county and sighting layers will become the MultiPolygon and Point PostGIS geometry columns, thanks to the GeoDjango library.

 

  1. Create an admin.py file under chp09/wildlife/sightings and add the following code to it. The classes in this file will define and customize the behavior of the Django admin site when browsing the application models or tables (fields to display, fields to be used to filter records, and fields to order records). Create the file by executing the following code:
        from django.contrib import admin 
        from django.contrib.gis.admin import GeoModelAdmin 
        from models import Country, Animal, Sighting 
 
        class SightingAdmin(GeoModelAdmin): 
          """ 
            Web admin behavior for the Sighting model. 
          """ 
          model = Sighting 
          list_display = ['date', 'animal', 'rate'] 
          list_filter = ['date', 'animal', 'rate'] 
          date_hierarchy = 'date' 
 
        class AnimalAdmin(admin.ModelAdmin): 
          """ 
            Web admin behavior for the Animal model. 
          """ 
          model = Animal 
          list_display = ['name', 'image_url',] 
 
        class CountryAdmin(GeoModelAdmin): 
          """ 
            Web admin behavior for the Country model. 
          """ 
          model = Country 
          list_display = ['isocode', 'name'] 
          ordering = ('name',) 
 
          class Meta: 
            verbose_name_plural = 'countries' 
 
        admin.site.register(Animal, AnimalAdmin) 
        admin.site.register(Sighting, SightingAdmin) 
        admin.site.register(Country, CountryAdmin)
  1. Now, to synchronize the database, execute the following commands in the Django project folder:
      (chp09-env)$ python manage.py makemigrations 
      (chp09-env)$ python manage.py migrate

The output should be as follows:

  1. Now, for each model in models.py, a PostgreSQL table should have been created. Check whether your PostgreSQL database effectively contains the three tables created in the preceding commands using your favorite client (that is, psql or pgAdmin) and whether or not the sightings_sighting and sightings_country tables contain PostGIS geometric fields.
  2. Any web application needs the definition of URLs where the pages can be accessed. Therefore, edit your urls.py file under chp09/wildlife/wildlife by adding the following code:
        from django.conf.urls import url
from django.contrib import admin
import settings
from django.conf.urls.static import static
admin.autodiscover()
urlpatterns = [
url(r'^admin/', admin.site.urls),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

In the urls.py file, you basically defined the location of the back office (which was built using the Django admin application) and the media (images) files' location uploaded by the Django administrator when adding new animal entities in the database. Now run the Django development server, using the following runserver management command:

      (chp09-env)$ python manage.py runserver
  1. Access the Django admin site at http://localhost:8000/admin/ and log in with the superuser credentials you furnished in an earlier step in this recipe (step 7).
  2. Now, navigate to http://localhost:8000/admin/sightings/animal/ and add some animals using the Add animal button. For each animal, define a name and an image that will be used by the frontend that you will build in the next recipe. You created this page with almost no code, thanks to the Django admin! The following screenshot shows what the Animals list page will look like after adding some entities:
  1. Navigate to http://localhost:8000/admin/sightings/sighting/ and add some sightings using the Add sighting button. For each sighting, define the Date, Time, the name of the animal that was spotted, Rate, and the location. GeoDjango has added the map widget to the Django Admin site for you, based on the OpenLayers JavaScript library, to add or modify geometric features. The Sightings page is shown in the following screenshot:
  1. The Sightings list page, thanks to the Django admin's efficiency, will provide the administrative user with useful features to sort, filter, and navigate the date hierarchy of all of the sightings in the system, as shown in the following screenshot:
  1. Now, you will import the countries shapefile to its model. In the next recipe, you will use this model to find the country where each sighting occurred. Before going ahead in this recipe, investigate the shapefile structure; you will need to import just the NAME and ISO2 attributes to the model as the name and isocode attributes, using the following command:
      $ ogrinfo TM_WORLD_BORDERS-0.3.shp TM_WORLD_BORDERS-0.3 -al -so
  1. Add a load_countries.py file under chp09/wildlife/sightings and import the shapefile to PostGIS, using the LayerMapping GeoDjango utility, using the following code:
        """ 
        Script to load the data for the country model from a shapefile. 
        """ 
 
        from django.contrib.gis.utils import LayerMapping 
        from models import Country 
 
        country_mapping = { 
          'isocode' : 'ISO2', 
          'name' : 'NAME', 
          'geometry' : 'MULTIPOLYGON', 
        } 
 
        country_shp = 'TM_WORLD_BORDERS-0.3.shp' 
        country_lm =  LayerMapping(Country, country_shp, country_mapping, 
                                   transform=False, encoding='iso-8859-1') 
        country_lm.save(verbose=True, progress=True) 
  1. You should have the TM_WORLD_BORDERS-0.3.shp file placed under chp09/wildlife for this code to work. Enter the Python Django shell and run the utils.py script. Then, check whether the countries have been correctly inserted in the sightings_country table in your PostgreSQL database, using the following command:
      (chp09-env)$ python manage.py shell
>>> from sightings import load_countries
Saved: Antigua and Barbuda
Saved: Algeria Saved: Azerbaijan
...
Saved: Taiwan

Now, you should see the countries in the administrative interface at http://localhost:8000/admin/sightings/country/, while running the Django server with:

      (chp09-env)$ python manage.py runserver