Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
Python Geospatial Analysis Cookbook
Python Geospatial Analysis Cookbook

Python Geospatial Analysis Cookbook: Over 60 recipes to work with topology, overlays, indoor routing, and web application analysis with Python

eBook
€8.99 €32.99
Paperback
€41.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
Table of content icon View table of contents Preview book icon Preview Book

Python Geospatial Analysis Cookbook

Chapter 2. Working with Projections

In this chapter, we will cover the following topics:

  • Discovering projection(s) of a Shapefile or GeoJSON dataset
  • Listing projection(s) from a WMS server
  • Creating a projection definition for a Shapefile if it does not exist
  • Batch setting the projection definition of a folder full of Shapefiles
  • Reprojecting a Shapefile from one projection to another

Introduction

Working with projections, in my opinion, is not too exciting but they're very important, and your ability to deal with them in any application is crucial.

The goal of this chapter is to provide some common predata screening or transformation steps to get your data in shape or, better yet, in position for geospatial analysis. We cannot always perform analysis on multiple datasets that are in different coordinate systems without the risk of achieving inconsistent results, such as data positional inaccuracies. Therefore, it is a best practice to work on data in the same coordinate system, such as EPSG:4326, when working on a global scale, or use a local coordinate system for your region that will provide you the most accurate results.

European Petroleum Survey Group or EPSG codes have decided to give all coordinate systems a number code to simplify finding and sharing projection information. Coordinate systems are described by their definitions, which are stored in text files...

Discovering projection(s) of a Shapefile or GeoJSON dataset

Remember that all data is stored in a coordinate system, no matter what the data source is. It is your job to figure this out using a simple approach outlined in this section. We will take a look at two different data storage types: a Shapefile and a GeoJSON file. These two formats contain geometries, such as points, lines, or polygons, and their associated attributes. For example, a tree would be stored as a point geometry with attributes, such as height, age, and species, Each of these data types store their projection data differently and, therefore, require different methods to discover their projection information.

Now a quick introduction to what a Shapefile is: a Shapefile is not a single file but a minimum of three files, such as .shp, .shx, and, .dbf, all of which have the same name. For example, world_borders.shp, world_borders.shx and world_borders.dbf make up one file. The .shp file stores geometry, .dbf stores a table...

Listing projection(s) from a WMS server

The Web Mapping Service (WMS), which can be found at https://en.wikipedia.org/wiki/Web_Map_Service, is fun since most service providers provide data in several coordinate systems and you can then specify which one you would like. However, you can't reproject or transform the WMS into some other system that the service provider does not provide, which means that you can only use the coordinate system that is provided. The following is an example of a WMS getCapabilities request (http://gis.ktn.gv.at/arcgis/services/INSPIRE/INSPIRE/MapServer/WmsServer?service=wms&version=1.3.0&request=getcapabilities), showing a list of the five available coordinate systems from a WMS service:

Listing projection(s) from a WMS server

Getting ready

The WMS service URL that we will use is http://ogc.bgs.ac.uk/cgi-bin/BGS_1GE_Geology/wms?service=WMS&version=1.3.0&request=GetCapabilities. This is from the British Geological Survey, titled OneGeology Europe geology.

Tip

For a list of WMS servers...

Creating a projection definition for a Shapefile if it does not exist

You recently downloaded a Shapefile from an Internet resource and saw that the .prj file was not included. You do know, however, that the data is stored in the EPSG:4326 coordinate system as stated on the website from where you downloaded the data. Now the following code will create a new .prj file.

Getting ready

Start up your Python virtual environment with the workon pygeo_analysis_cookbook command:

How to do it...

In the following steps, we will take you through creating a new .prj file to accompany our Shapefile. The .prj extension is necessary for many spatial operations performed by a desktop GIS, web service, or script:

  1. Create a new Python file named ch02_04_write_prj_file.py in your /ch02/code/working/ directory and add the following code:
    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    
    import urllib
    import os
    
    def get_epsg_code(epsg):
       """
       Get the ESRI formatted .prj definition
       usage get_epsg_code...

Batch setting the projection definition of a folder full of Shapefiles

Working with one Shapefile is fine but working with tens or hundreds of files is something else. In such a scenario, we'll need automation to get a job done fast.

We have a folder that contains several Shapefiles that are all in the same coordinate system but do not have a .prj file. We want to create a .prj file for each Shapefile in the current directory.

This script is a modified version of the previous code example that could write a .prj file for a single Shapefile into a batch process that can run over several Shapefiles.

How to do it...

We have a folder with many Shapefiles and we would like to create a new .prj file for each Shapefile in this folder, so let's get started:

  1. Create a new Python file named ch02_05_batch_shp_prj.py in your /ch02/code/working/ directory and add the following code:
    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    
    import urllib
    import os
    from osgeo import osr
    
    
    def create_epsg_wkt_esri...

Reprojecting a Shapefile from one projection to another

Working with spatial data from multiple sources leads to data that's most likely from multiple regions on Earth with multiple coordinate systems. To perform consistent spatial analysis, we should transform all our input data into the same coordinate system. This means reprojecting your Shapefile into your chosen working coordinate system.

In this recipe, we will reproject a single Shapefile from ESPG:4326 into a web mercator system EPSG:3857 for use in a web application.

How to do it...

Our goal is to reproject a given Shapefile from one coordinate system to another; the steps to do this are as follows:

  1. Create a new Python file named ch02_06_re_project_shp.py in your /ch02/code/working/ directory and add the following code:
    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    
    import ogr
    import osr
    import os
    
    shp_driver = ogr.GetDriverByName('ESRI Shapefile')
    
    # input SpatialReference
    input_srs = osr.SpatialReference()
    input_srs...
Left arrow icon Right arrow icon

Description

Geospatial development links your data to places on the Earth’s surface. Its analysis is used in almost every industry to answer location type questions. Combined with the power of the Python programming language, which is becoming the de facto spatial scripting choice for developers and analysts worldwide, this technology will help you to solve real-world spatial problems. This book begins by tackling the installation of the necessary software dependencies and libraries needed to perform spatial analysis with Python. From there, the next logical step is to prepare our data for analysis; we will do this by building up our tool box to deal with data preparation, transformations, and projections. Now that our data is ready for analysis, we will tackle the most common analysis methods for vector and raster data. To check or validate our results, we will explore how to use topology checks to ensure top-quality results. This is followed with network routing analysis focused on constructing indoor routes within buildings, over different levels. Finally, we put several recipes together in a GeoDjango web application that demonstrates a working indoor routing spatial analysis application. The round trip will provide you all the pieces you need to accomplish your own spatial analysis application to suit your requirements.

Who is this book for?

If you are a student, teacher, programmer, geospatial or IT administrator, GIS analyst, researcher, or scientist looking to do spatial analysis, then this book is for you. Anyone trying to answer simple to complex spatial analysis questions will get a working demonstration of the power of Python with real-world data. Some of you may be beginners with GIS, but most of you will probably have a basic understanding of geospatial analysis and programming.

What you will learn

  • Discover the projection and coordinate system information of your data and learn how to transform that data into different projections
  • Import or export your data into different data formats to prepare it for your application or spatial analysis
  • Use the power of PostGIS with Python to take advantage of the powerful analysis functions
  • Execute spatial analysis functions on vector data including clipping, spatial joins, measuring distances, areas, and combining data to new results
  • Create your own set of topology rules to perform and ensure quality assurance rules in Python
  • Find the shortest indoor path with network analysis functions in easy, extensible recipes revolving around all kinds of network analysis problems
  • Visualize your data on a map using the visualization tools and methods available to create visually stunning results
  • Build an indoor routing web application with GeoDjango to include your spatial analysis tools built from the previous recipes

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Nov 30, 2015
Length: 310 pages
Edition : 1st
Language : English
ISBN-13 : 9781783555079
Category :
Languages :

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details

Publication date : Nov 30, 2015
Length: 310 pages
Edition : 1st
Language : English
ISBN-13 : 9781783555079
Category :
Languages :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
€189.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
€264.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 125.97
Learning Geospatial Analysis with Python-Second Edition
€41.99
Python Geospatial Analysis Cookbook
€41.99
Python Geospatial Development
€41.99
Total 125.97 Stars icon
Banner background image

Table of Contents

14 Chapters
1. Setting Up Your Geospatial Python Environment Chevron down icon Chevron up icon
2. Working with Projections Chevron down icon Chevron up icon
3. Moving Spatial Data from One Format to Another Chevron down icon Chevron up icon
4. Working with PostGIS Chevron down icon Chevron up icon
5. Vector Analysis Chevron down icon Chevron up icon
6. Overlay Analysis Chevron down icon Chevron up icon
7. Raster Analysis Chevron down icon Chevron up icon
8. Network Routing Analysis Chevron down icon Chevron up icon
9. Topology Checking and Data Validation Chevron down icon Chevron up icon
10. Visualizing Your Analysis Chevron down icon Chevron up icon
11. Web Analysis with GeoDjango Chevron down icon Chevron up icon
A. Other Geospatial Python Libraries Chevron down icon Chevron up icon
B. Mapping Icon Libraries Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.4
(5 Ratings)
5 star 40%
4 star 60%
3 star 0%
2 star 0%
1 star 0%
Christian S. Dec 14, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Chapter 1 does a good job in getting you up and running with Python and the main libraries used in the following chapters.Chapter 2 explains coordinate systems and introduces Shapefile and GeoJSON file formats. Chapter 3 continues explaining image formats such as raster and vector. Also we setup our PostgreSQL and PostGIS. The instruction are clear and easy to follow. An interesting example is the conversion of an OpenStreeMap to a Shapefile. In Chapter 4 the focus is on PostGIS.Chapter 5, 6 and 7 deal with vector and geometry analysis. There are examples to calculate intersections, distances, and operations between polygons.Chapter 8 explains network analysis. There are very interesting examples on how to calculate the shortest path and an example to calculate indoor route walk time. Definitely this was one of the most interesting chapters.Chapter 9 deals with topology and validations rules. It has several example algorithms to validate rules.Chapter 10 and 11 finalize the implementation of the previous chapters, dealing with the final presentation through visualizations for the web.In summary I would recommend this book, it has enough content to serve as a reference to find examples in which you can dig deeper. This is a more practical book in the sense that you will not find detailed explanations of the algorithms, and it uses several third party libraries in the examples to get the job done.One thing it could have been improved is the layout of the source code.
Amazon Verified review Amazon
DC_ Jan 05, 2016
Full star icon Full star icon Full star icon Full star icon Full star icon 5
The first chapter regarding getting everything setup is quite thorough regarding setting up the various Python libraries that are needed throughout the book. I found chapter 8 on network analysis very useful and interesting. This books gives a good grounding with code examples on which to build.
Amazon Verified review Amazon
Amazon Kunde Jun 04, 2019
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
A very helpful book, gives practical directions tp script useful applications within the field of geospatial analyses. However, some scripts could be a bit better explained for real beginners.
Amazon Verified review Amazon
Amazon Customer Dec 28, 2015
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
Great introduction to a variety of Python libraries available for geospatial analysis. Both vector and raster analysis is covered with interesting examples. Many of the recipes will act as a base for the reader to take snippets from and build upon to implement into their own workflows. Algorithms and code not heavily explained which might not be great for complete beginners. Overall I recommend this book as it will open your eyes to some of the geospatial analysis techniques that you may not have realised were easy to implement outside of a standard GIS software package.
Amazon Verified review Amazon
USHANT SUMAN Dec 07, 2015
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
Nice book readymade recipes for many day to day work.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.