Getting Started with PostGIS
Send me Nitor Infotech's Monthly Blog Newsletter!
×
Software Product Engineering Services Company
  • Company
    • About
    • Leadership
    • Partnership
  • Resource Hub
  • Blog
  • Contact
Software Product Engineering Services Company
Add more content here...
Artificial intelligence Big Data Blockchain and IoT
Business Intelligence Cloud and DevOps Digital Transformation
Healthcare IT Manufacturing Mobility
Product Modernization Software Engineering Thought Leadership
Aastha Sinha Abhijeet Shah Abhishek Suranglikar
Abhishek Tanwade Ajinkya Pathak Amol Jadhav
Ankita Kulkarni Antara Datta Anup Manekar
Chandra Gosetty Chandrakiran Parkar Dr. Girish Shinde
Gaurav Rathod Harshali Chandgadkar Madhavi Pawar
Mohit Agarwal Mohit Borse Nalini Vijayraghavan
Neha Garg Omkar Ingawale Omkar Kulkarni
Pranit Gangurde Priya Patole Ravi Agrawal
Robin Pandita Rohini Wwagh Sachin Saini
Sadhana Sharma Sambid Pradhan Sanjeev Fadnavis
Shailesh Banaeet Shardul Gurjar Shravani Dhavale
Shubham Hedau Shubham Kamble Shubham Muneshwar
Sidhant Naveria Sujay Hamane Tejbahadur Singh
Tushar Sangore Vasishtha Ingale Veena Metri
Vidisha Chirmulay
Big Data | 19 Jan 2022 |   9 min

Getting Started with PostGIS

If you have worked with geospatial data, you would possibly want to harness the power of PostGIS. In case you haven’t, do check out my previous blog to gain an understanding of geospatial data. PostGIS is an extension of PostgreSQL which adds spatial ability to your database. Reading, analyzing, and processing geospatial files (viz. .shp, .tif) requires special tools. However, conducting SQL operations to achieve the same makes it more consistent for developers.

PostGIS allows you to load and query geospatial data from the database for representational purposes very easily. This blog is going to give you all the help to get you started with PostGIS, including installation steps for Windows and Linux. Read on to understand the process:

Installation for Windows

Before you put your PostGIS lab goggles on, you need to have all the precursors in place and that includes mainly having your windows installed. Here’s how you get that done:

  1. Install Postgres on the system using: https://www.enterprisedb.com/downloads/postgres-postgresql-downloads.
  2. It adds Stack Builder to your system automatically, run Stack Builder to set up PostGIS.

3. Select the PostGIS bundle and hit next.

4. Follow the steps given in the setup to complete the installation.

Setting up PostGIS

Once the installation steps are completed, go to pgAdmin or any other database client and create a new database. Postgres by default contains one extension i.e., plpgsql. To add PostGIS as an extension, run the following query on your database.

create extension postgis;

After running the above query, a new extension will be added which can be viewed under the extensions.

Along with this extension, a new table named ‘spatial_ref_sys’ with srids and projections will be created. This table contains all spatial references and is used for transformations.

Installation for Linux

1. Refresh the local package index.

sudo apt-get update

2. Install the Postgres package along with contrib that adds some additional utilities and functionality.

sudo apt install postgresql-11 postgresql-contrib

4. Install the PostGIS package on the system.

sudo apt-get install postgis

4. Connect to a database.

psql -d <database>

5. Next, enable the PostGIS extension on the database. PostGIS’s features need to be activated on a per-database basis before you can store spatial data.

CREATE EXTENSION postgis;

6. Verify that everything worked correctly.

SELECT PostGIS_version();

You’ll see this output:

        postgis_version 
       ---------------------------------------
3.0 USE_GEOS=1 USE_PROJ=1 USE_STATS=1(1 row)

Loading data

Geospatial data can be loaded in different ways based on the kind of files that are storing them. For now, we will consider shapefiles, a widely used form of storing vector data. Shapefiles can be loaded into the database in the following two ways:

1.Using PostGIS Bundle

a. Look for “postgis bundle 3 for PostgreSQL x64 Shapefile and DBF” in your applications, it is usually downloaded with PostGIS. Use the PostGIS extension to connect to your newly created database by adding details such as hostname, port and database name. On successful connection, you will see the following message:

Connecting:  host=localhost port=5433 user=postgres password=’********’ dbname=test client_encoding=UTF8

Connection succeeded

b. Now click on ‘Import’ and select ‘Add File’. Select all the shape files you would like to import.

c. Add the SRID if it is missing and click on ‘Import’. This will import each shape file as a relational model in your database.

d. On describing any of these tables, you will be able to see the columns along with the geom column which represents the actual geospatial information. It comprises the latitude and longitude.

In order to view the data, you will need to query the geom column from any of the tables:

2. Using command line

The standard tool for loading shape file is “shp2pgsql”. It can be found in the bin folder of the Postgres installation. This is how it can be used:

shp2pgsql [<options>] <shapefile> [[<schema>.]<table>]
shp2pgsql -s 4326 subway_stations public.nyc_subway_stations | psql -h localhost -p 5433 -U postgres -d test

Querying data

This data can be queried in many forms to generate the desired visualizations. A geom can either be a POINT, LINESTRING, POLYGON or a combination of these. Various operations like calculating the distance between two points, area, intersection etc. can be queried from the data using certain predefined postgis methods. Some of the commonly used methods are: ST_Length, ST_Area, ST_Contains, ST_Intersection, ST_Equals, ST_Within, ST_Scale, ST_Translate.

One of the most widely used and accepted formats of geospatial data that can be integrated with maps like leaflet is called geoJSON. PostGIS can be directly queried to generate response in the geoJSON format like:

select  
json_build_object( 'type', 'FeatureCollection', 'features', json_agg(st_asgeojson(t.*)::json))
  from 
(select gid, name, geom from ${tablename} ) as t(id, name, geom);

This is how an actual geoJSON looks:

{
    "type": "FeatureCollection",
    "features": [
        {
            "type": "Feature",
            "geometry": {
                "type": "Point",
                "coordinates": [
                    -76.935256783,
                    38.9081784965
                ]
            },
            "properties": {
                "gid": 1,
                "name": "one"
            }
        },
        {
            "type": "Feature",
            "geometry": {
                "type": "Point",
                "coordinates": [
                    -76.9750541388,
                    38.8410857803
                ]
            },
            "properties": {
                "gid": 2,
                "name": "two"
            }
        }
    ]
}

A lot of modern tools today rely on geospatial data. PostGIS can provide insights by using these methods of storing and querying such data with greater ease.

Reach out to us or visit Nitor Infotech if you have any comments or suggestions related to this topic. My upcoming final blog in this series will introduce you to GeoServer, so keep watching this space!

Related Topics

Artificial intelligence   Big Data   Blockchain and IoT   Business Intelligence   Cloud and DevOps   Digital Transformation   Healthcare IT   Manufacturing   Mobility   Product Modernization   Software Engineering   Thought Leadership  
<< Previous Blog Next Blog >>

Antara Datta

Associate Architect

Antara Datta has been working at Nitor Infotech for over 6 years and has worked on multiple technologies and domains. She is a full stack programmer, an open source enthusiast and a fan of innovation and technology. She enjoys figuring out solutions to problems with different problem-solving techniques.

   

You may also like

AWS Machine Learning: Part 1

Machine learning has grown to be quite the popular trendsetter in recent years for different organizations. Hence, it is unsurprising to see major cloud companies coming up with custom cloud sol...
Read Blog


The Three Cornerstones of Enterprise Transformation

Heightened customer expectations and the need to survive in volatile markets have set businesses on a quest to become more agile, resilient, and relevant. To achieve these goals, it is crucial for ...
Read Blog


Insights on Diving into Data Analytics

As I begin writing this blog, I am pulled down memory lane where these famous lines from the poem ‘The Rime of the Ancient Mariner’ penned by Coleridge echo: ‘Water, water everywhere but not a d...
Read Blog


Subscribe to Our Blog

Services

    Modern Software Engineering


  • Idea to MVP
  • Quality Engineering
  • Product Engineering
  • Product Modernization
  • Reliability Engineering
  • Product Maintenance

    Enterprise Solution Engineering


  • Idea to MVP
  • Strategy & Consulting
  • Enterprise Architecture & Digital Platforms
  • Solution Engineering
  • Enterprise Cognition Engineering

    Digital Experience Engineering


  • UX Engineering
  • Content Engineering
  • Peer Product Management
  • RaaS
  • Mobility Engineering

    Technology Engineering


  • Cloud Engineering
  • Cognitive Engineering
  • Blockchain Engineering
  • Data Engineering
  • IoT Engineering

    Industries


  • Healthcare
  • Retail
  • Manufacturing
  • BFSI

    Company


  • About
  • Leadership
  • Partnership
  • Contact Us

    Resource Hub


  • White papers
  • Brochures
  • Case studies
  • Datasheet

    Explore More


  • Blog
  • Career
  • Events
  • Press Releases

About


With more than 15 years of experience in handling multiple technology projects across industries, Nitor Infotech has gained strong expertise in areas of technology consulting, solutioning, and product engineering. With a team of 700+ technology experts, we help leading ISVs and Enterprises with modern-day products and top-notch services through our tech-driven approach. Digitization being our key strategy, we digitally assess their operational capabilities in order to achieve our customer's end- goals.

Get in Touch


  • +1 (224) 265-7110
  • marketing@nitorinfotech.com

We are Social 24/7


© 2022 Nitor Infotech All rights reserved

  • Terms of Usage
  • Privacy Policy
  • Cookie Policy
x
We use cookies to ensure that we give you the best experience on our website. If you continue to use this site we will assume that you are happy with it. Accept Cookie policy