How to Use PostGIS in ServBay: Adding Geospatial Capabilities to PostgreSQL
PostGIS
is a powerful PostgreSQL database extension that adds support for geospatial data types, functions, and indexes. With it, you can store geographic information such as points, lines, and polygons in your database, and perform complex spatial queries and analyses. For developers working with maps, location services, or any web applications involving geographic information, PostGIS is an indispensable tool.
ServBay, a local web development environment designed for macOS, comes with a bundled PostgreSQL package and, by default, includes the PostGIS extension. This greatly simplifies the process of using PostGIS locally—there’s no need to compile or install additional dependencies manually.
This guide will walk you through enabling and using PostGIS in the ServBay environment, helping you quickly add geospatial features to your project.
Prerequisites
Before using PostGIS, make sure you’ve completed the following preparations:
- Install and Run ServBay: Ensure you have ServBay successfully installed on your macOS system.
- Enable and Start the PostgreSQL Package: Confirm on the ServBay control panel that the PostgreSQL package is enabled and running. If it’s not enabled yet, locate PostgreSQL on the ServBay control panel, check "Enable," and then start the package.
- Access the PostgreSQL Database: Know how to connect to the PostgreSQL database running in ServBay either via the command-line tool
psql
or with a GUI client (such as TablePlus or pgAdmin). By default, you can connect to the local database withpsql -U postgres
.
Installing and Enabling the PostGIS Extension
ServBay includes the PostGIS extension files out of the box; no extra downloads are necessary. All you need to do is “enable” the extension in the specific database where you want to use PostGIS.
Here are the steps to enable the PostGIS extension:
Connect to Your Target PostgreSQL Database: Open your Terminal and connect using the
psql
command, replacingyour_username
with your database username (e.g.,postgres
) andyour_database
with your chosen database name.bashpsql -U your_username -d your_database
1To enable PostGIS in the default
postgres
user and database, simply run:bashpsql -U postgres
1Create the PostGIS Extension in Your Database: Once connected, execute the following SQL command in the
psql
command-line interface:sqlCREATE EXTENSION postgis;
1This command will install and configure all necessary objects (such as new data types, functions, operators, etc.) required for the PostGIS extension in your connected database.
Verify PostGIS Installation: To list all installed extensions in your current database, use the
\dx
command inpsql
:sql\dx
1If PostGIS was successfully enabled, you will see a
postgis
entry and its version in the list.List of installed extensions Name | Version | Schema | Description -----------+---------+------------+-------------------------------------------------------------- plpgsql | 1.0 | pg_catalog | PL/pgSQL procedural language postgis | 3.3.2 | public | PostGIS geometry and geography spatial types and functions (2 rows)
1
2
3
4
5
6(Note: The PostGIS version may vary depending on your version of ServBay.)
You have now successfully enabled the PostGIS extension for your specified PostgreSQL database and are ready to use its geospatial features.
Configuring PostGIS Data
Once PostGIS is enabled, you can create new tables with geospatial data or add spatial columns to existing tables. PostGIS provides two primary spatial data types: geometry
and geography
. The geometry
type is used for calculations in a planar coordinate system, while geography
is for spherical coordinate systems (such as Earth's surface), making it ideal for lat/lng data.
Creating a Table With a Spatial Column
Here is an example of how to create a locations
table with a spatial column for storing point locations.
Create Table: Run the following in the
psql
CLI or your favorite database GUI:sqlCREATE TABLE locations ( id SERIAL PRIMARY KEY, name VARCHAR(100), geom GEOMETRY(Point, 4326) );
1
2
3
4
5GEOMETRY(Point, 4326)
: Defines ageom
column of typeGEOMETRY
, specifically for storing points.4326
is the SRID (Spatial Reference Identifier) for the WGS84 coordinate system, which is the standard lat/lng system used by GPS and many online maps (e.g., OpenStreetMap, Google Maps).- You can use other geometry types (such as
LineString
,Polygon
,MultiPoint
) and SRIDs as needed.
Insert Sample Data: Use PostGIS-provided functions to insert geometry objects into the table. The
ST_GeomFromText()
function is commonly used to create geometry from WKT (Well-Known Text) strings.sqlINSERT INTO locations (name, geom) VALUES ('ServBay Headquarters', ST_GeomFromText('POINT(116.4074 39.9042)', 4326)), -- Example: Beijing coordinates ('ServBay Shanghai Office', ST_GeomFromText('POINT(121.4737 31.2304)', 4326)); -- Example: Shanghai coordinates
1
2
3Note: In the WKT standard,
POINT(lon lat)
order is longitude first.
Creating a Spatial Index
For tables with lots of spatial data, spatial indexes greatly boost query performance—especially for range, containment, or nearest-neighbor searches. The most common spatial index in PostGIS is GiST (Generalized Search Tree).
Create a GiST Index: Execute:
sqlCREATE INDEX idx_locations_geom ON locations USING GIST (geom);
1This creates a GiST index on the
geom
column in thelocations
table. PostgreSQL’s query planner will automatically use this index for spatial queries.
Performing Geospatial Queries With PostGIS
PostGIS provides hundreds of functions for various geospatial operations. Here are some common query examples for web developers:
Calculating the Distance Between Two Points
Calculate straight-line distance between two locations.
SELECT ST_Distance(
ST_GeomFromText('POINT(116.4074 39.9042)', 4326), -- Point A
ST_GeomFromText('POINT(121.4737 31.2304)', 4326) -- Point B
);
2
3
4
ST_Distance()
: Calculates the distance between two geometries. Forgeometry
type with SRID 4326, the result is in degrees (approximate). For more precise, meter-based distances, use thegeography
type orST_Distance(geography_a, geography_b, use_spheroid)
.
Checking Containment
Determine if one geometry contains another, e.g., checking if a point is inside a specific area (polygon).
SELECT name FROM locations
WHERE ST_Contains(
ST_GeomFromText('POLYGON((116.0 39.0, 117.0 39.0, 117.0 40.0, 116.0 40.0, 116.0 39.0))', 4326), -- Example rectangle
geom
);
2
3
4
5
ST_Contains(geometry A, geometry B)
: Returns true if geometry A completely contains geometry B.
Nearest Neighbor Search
Find the locations closest to a given point. With a GiST index, this is highly efficient.
SELECT name, ST_Distance(geom, ST_GeomFromText('POINT(116.4074 39.9042)', 4326)) AS distance
FROM locations
ORDER BY geom <-> ST_GeomFromText('POINT(116.4074 39.9042)', 4326) -- Use <-> operator to leverage GiST index
LIMIT 5;
2
3
4
<->
is a special PostGIS “distance” operator for quick nearest-neighbor queries using the GiST index.
Geospatial Analysis With PostGIS
In addition to basic queries, PostGIS offers powerful analysis capabilities such as buffer creation, intersection, geometry union, and more.
Buffer Analysis
Create a buffer area (polygon) around a geometry at a specified distance.
SELECT ST_Buffer(geom, 0.01) -- Buffer at 0.01 degrees (~1.1 km)
FROM locations
WHERE name = 'ServBay Headquarters';
2
3
ST_Buffer(geometry, distance)
: Creates a buffer of the given distance. Forgeometry
type in geographic coordinates, distance is in degrees.
Intersection Analysis
Compute the overlapping part of two or more geometries and return a new geometry.
SELECT ST_Intersection(
ST_GeomFromText('POLYGON((116.0 39.0, 117.0 39.0, 117.0 40.0, 116.0 40.0, 116.0 39.0))', 4326),
geom
)
FROM locations
WHERE name = 'ServBay Headquarters';
2
3
4
5
6
ST_Intersection(geometry A, geometry B)
: Returns the intersection of A and B as a new geometry.
Union Analysis
Merge multiple geometries into a single (possibly multi-part) geometry.
SELECT ST_Union(geom)
FROM locations;
2
ST_Union(geometry set)
: Merges all geometries in the input set.
Visualizing Geospatial Data
Visualizing geospatial data stored in a PostGIS database is a common web development need. You can use either desktop GIS software or web mapping libraries.
Using Desktop GIS Tools (e.g., QGIS)
QGIS is a popular open-source desktop GIS tool that can connect directly to a PostGIS database and visualize your spatial data.
Connect to ServBay's PostgreSQL Database:
- Open QGIS.
- In the menu, go to
Layer
->Add Layer
->Add PostGIS Layers...
. - In the window that appears, click
New
to create a new database connection. - Enter the connection details:
- Name: Give your connection a name, e.g.,
ServBay PostGIS
. - Host:
localhost
or127.0.0.1
. - Port: Default PostgreSQL port is
5432
(also ServBay's default). - Database: The name of the database where you've enabled PostGIS.
- Username: Your DB username (e.g.,
postgres
). - Password: Your password (if set).
- Name: Give your connection a name, e.g.,
- Click
Test Connection
to verify successful connection. - Click
OK
to save, then clickConnect
in the main window.
Load Geospatial Data:
- Once connected, you'll see all tables in your database.
- Find a table with a spatial column (e.g.,
locations
). QGIS will recognize spatial columns automatically. - Select the table you want to load, click
Add
, then clickClose
. Your geospatial data will display in the QGIS map view.
Using Web Mapping Libraries (e.g., Leaflet)
On the front end, you can use JavaScript map libraries (like Leaflet, OpenLayers, Mapbox GL JS) to display geospatial data fetched via API from your backend—such as GeoJSON data from PostGIS. Here’s a basic Leaflet example that loads a map in an HTML file. You’ll need to create backend services (using PHP, Node.js, Python, etc.; all supported in ServBay) to fetch spatial data from PostGIS and return it in GeoJSON for the frontend.
Save the following HTML file in a subdirectory of ServBay's web root (default: /Applications/ServBay/www
), for instance /Applications/ServBay/www/postgis-map/index.html
. Then access your local site via ServBay (e.g., postgis-map.servbay.demo
).
<!DOCTYPE html>
<html>
<head>
<title>ServBay PostGIS Leaflet Example</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://unpkg.com/leaflet/dist/leaflet.css" />
<script src="https://unpkg.com/leaflet/dist/leaflet.js"></script>
<style>
#map { height: 400px; width: 100%; } /* Set container size */
</style>
</head>
<body>
<h1>PostGIS Data Visualization Example (Leaflet)</h1>
<div id="map"></div>
<script>
// Initialize map with center and zoom
// Example center: near Beijing
var map = L.map('map').setView([39.9042, 116.4074], 10);
// Add OpenStreetMap layer
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© OpenStreetMap contributors'
}).addTo(map);
// Example: manually add a marker (real use would load from PostGIS dynamically)
// This point matches the 'ServBay Headquarters' example inserted above
var marker = L.marker([39.9042, 116.4074]).addTo(map)
.bindPopup('<b>ServBay Headquarters</b><br>Example location')
.openPopup();
// In a real project, fetch data from backend (typically GeoJSON) and add to map
/*
fetch('/api/locations') // Suppose your backend provides '/api/locations' returning GeoJSON
.then(response => response.json())
.then(data => {
L.geoJSON(data).addTo(map);
});
*/
</script>
</body>
</html>
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
This is just a basic usage of Leaflet. To load data from a PostGIS database, you’ll need backend code to fetch spatial data, convert it to GeoJSON, and expose it via an HTTP API to your frontend. ServBay's support for multiple backend languages makes this process convenient.
FAQ
Q: What if I get an error running
CREATE EXTENSION postgis;
?- A: First, make sure you’re connected to the PostgreSQL database and that your user account has permission to create extensions (typically, the
postgres
user does). Also, check that the PostgreSQL package in ServBay is running. If the problem persists, reviewing the ServBay and PostgreSQL log files may provide more details.
- A: First, make sure you’re connected to the PostgreSQL database and that your user account has permission to create extensions (typically, the
Q: What is SRID 4326, and can I use other SRIDs?
- A: SRID (Spatial Reference Identifier) is a numeric code uniquely identifying a coordinate reference system. 4326 is for the WGS84 geographic coordinate system, which is the most widely used for web mapping. Yes, you can use other SRIDs, such as projected coordinate systems (e.g., Web Mercator, SRID 3857). The appropriate SRID depends on your data source and app needs. For lat/lng web map display, 4326 or 3857 is a solid choice.
Q: What’s the difference between
geometry
andgeography
types?- A: The
geometry
type is for planar Cartesian coordinates—distance and area calculations use Euclidean geometry. Thegeography
type is for spherical coordinates (like lat/lng on the Earth's surface)—distance and area calculations account for Earth’s curvature and are more accurate, especially for large areas. If working with small areas or don’t require curvature-corrected calculations,geometry
is simpler and sometimes faster. For global lat/lng data and precise measurements, usegeography
.
- A: The
Summary
PostGIS brings advanced geospatial processing power to PostgreSQL and is the foundation for building location-aware applications. With ServBay, enabling and using PostGIS on your local macOS environment is easy—no complicated installs or config required.
This article covered enabling the PostGIS extension on ServBay, creating and managing spatial data, running common spatial queries and analyses, and briefly discussed visualization options. By mastering these basics, you'll be ready to develop feature-rich geospatial web applications with PostGIS in ServBay. Dive into the PostGIS documentation to discover even more powerful functions and features.