PostGIS spatial queries: a practical guide for developers
Learn to write PostGIS spatial queries — ST_Distance, ST_Within, ST_Intersects, and spatial indexing. Practical examples for real-world geospatial apps.
PostGIS spatial queries: a practical guide for developers
PostGIS serves as the backbone of advanced geospatial processing, allowing developers to execute complex spatial queries with ease. Whether you are trying to find the nearest point of interest or measuring distances between geographical locations, understanding how to leverage PostGIS functions will empower you to build richer, more location-aware applications. This guide dives into essential PostGIS spatial queries and provides practical examples for implementation.
Introduction to PostGIS functions
PostGIS extends PostgreSQL with geospatial capabilities, offering a variety of functions that enhance your ability to manipulate spatial data. In this guide, we’ll explore foundational functions such as ST_Distance, ST_Within, and ST_DWithin. Along with these spatial queries, we’ll discuss spatial indexing to optimize query performance, focusing on GIST indexes and the distinctions between geography and geometry types.
ST_Distance function
The ST_Distance function calculates the distance between two geometry or geography objects. This function is useful in applications where finding proximity is required, such as determining the nearest restaurant or landmark.
Example
SELECT ST_Distance(
ST_MakePoint(-73.9857, 40.7484),
ST_MakePoint(-122.4194, 37.7749)
) AS distance;
In this instance, the ST_MakePoint function generates points representing geographic locations (longitude and latitude). The ST_Distance function will return the distance between the two coordinates in units consistent with the coordinate reference system used—in this case, meters if using geography data.
ST_Within function
The ST_Within function checks if one geometry is within another geometry. This can help to determine if a point lies within a specific area, like checking whether a user is within a designated district.
Example
SELECT ST_Within(
ST_MakePoint(-73.9857, 40.7484),
ST_MakePolygon(ST_MakeLine(ARRAY[
ST_MakePoint(-74, 40.7),
ST_MakePoint(-74, 40.8),
ST_MakePoint(-73.9, 40.8),
ST_MakePoint(-73.9, 40.7),
ST_MakePoint(-74, 40.7)
]))
) AS is_within;
In this example, the resulting boolean value of is_within indicates whether the point lies within the defined polygon.
ST_DWithin function
When you want to check if two geometries are within a certain distance from each other, ST_DWithin is the function to use. This function returns true if the geometries are closer than the specified distance.
Example
SELECT ST_DWithin(
ST_MakePoint(-73.9857, 40.7484),
ST_MakePoint(-122.4194, 37.7749),
5000000
) AS within_distance;
In this query, we're determining if the two points are within 5,000,000 meters (5,000 kilometers) of each other, returning a boolean result.
Spatial indexing with GIST
When working with spatial data, performance can dwindle due to the sheer volume of data. To enhance query speeds, employing a Generalized Search Tree (GIST) index is crucial for spatial columns.
Creating a GIST index
CREATE INDEX locations_geom_idx ON locations USING GIST (geom);
Once created, this index will significantly improve query performance for spatial functions like ST_Within and ST_DWithin.
Geography vs geometry types
PostGIS supports two primary spatial data types: geometry and geography. Understanding the differences between these two is vital for optimizing performance and accuracy.
- Geometry: Represents planar (flat) coordinates. Best for local, small-scale applications that do not require geodesic calculations.
- Geography: Represents spherical coordinates. Best for global-scale applications that require accurate distance measurements on the Earth's surface.
Choosing between types
- Use geography when dealing with long-distance measurements to ensure a more accurate representation of the Earth’s curvature.
- Use geometry for applications limited to a smaller geographic area where performance is prioritized.
Practical SQL examples
Combining these functions and index strategies allows you to create efficient SQL queries tailored to your application's needs. Here’s a comprehensive example that makes use of both the ST_DWithin function and a GIST index:
SELECT name
FROM parks
WHERE ST_DWithin(
geom,
ST_MakePoint(-73.9857, 40.7484),
1000
);
This query retrieves the names of parks within 1 kilometer from a specific point, utilizing the GIST index for improved performance.
Conclusion
By mastering PostGIS spatial queries, developers can create tailored applications that effectively utilize geospatial data. Start by implementing and testing these functions in your projects to enhance your understanding and boost application performance.
For those seeking additional hosted alternatives beyond self-hosting options like PostGIS, consider services such as Carto or Mapsi, which provide powerful geospatial infrastructure with ready-to-use APIs.
FAQ
See also
Start building with Mapsi — free
No credit card required. Free tier includes 10,000 requests/month.
curl "https://api.mapsi.dev/geocode?q=Berlin&key=YOUR_KEY" - EU-hosted on Hetzner — GDPR compliant
- Open-source core — Pelias + Valhalla
- Store results forever — no lock-in