Indoor routing and navigation using pgrouting and postgis
Table of Contents
- 1. The Growing Need for Precise Indoor Navigation
- 2. Why Indoor Navigation is Fundamentally Different from Outdoor GPS
- 3. Introduction to PostGIS and pgRouting
- 4. Essential Data Requirements for Indoor Routing
- 5. Digitizing and Capturing Indoor Spaces
- 6. Designing the Network Schema: Nodes and Edges
- 7. Addressing 3D Space and Multi-Floor Routing
- 8. Creating Network Topology with pgRouting
- 9. Implementing Accessibility, Barriers, and Cost Metrics
- 10. Writing the Routing Queries with Dijkstra and A*
- 11. Real-World Use Case: Navigating a Complex Hospital Campus
- 12. Real-World Use Case: Airport Passenger Flow Management
- 13. Integrating Indoor Routing with Web Mapping Applications
- 14. Integrating Real-Time Positioning Systems (IPS)
- 15. Optimizing pgRouting Performance for Large Facilities
- 16. Maintenance, Updates, and Dynamic Routing Environments
- 17. Future Trends in Indoor GIS and Navigation
- 18. Conclusion
rsandgis.me
The modern world is increasingly defined by massive, complex infrastructures such as sprawling hospital campuses, multi-terminal airports, and expansive shopping malls. While outdoor navigation has been largely solved by traditional GPS and web mapping services, guiding users through complex indoor environments remains a highly specialized challenge. In this comprehensive guide, we will explore the fundamentals of indoor routing and navigation using pgrouting and postgis. By leveraging the power of spatial databases, developers and GIS professionals can construct highly accurate, scalable, and fully customized indoor routing engines that solve the unique topological challenges of multi-floor, highly compartmentalized facilities.
1. The Growing Need for Precise Indoor Navigation
As buildings grow larger and more intricate, the demand for precise indoor navigation has skyrocketed. Visitors to a major hospital often experience stress when trying to find a specific ward, clinic, or testing center. Travelers rushing through international airports need to know the fastest route to their departure gate, accounting for security checkpoints, elevators, and moving walkways. The lack of reliable GPS signals indoors means that traditional outdoor navigation tools are fundamentally useless inside these structures. This creates a strong demand for customized indoor routing engines that can operate independently of satellite networks and provide pinpoint accuracy down to the meter.
Unlike outdoor environments, which are mostly flat or represented in 2D space on standard road networks, indoor spaces exist in three dimensions. Floors are stacked on top of one another, separated by barriers, and only accessible through specific chokepoints like stairs, escalators, and elevators. Designing a routing engine that understands this structural complexity requires a robust database solution. This is where PostgreSQL, enhanced with spatial and routing capabilities, becomes an invaluable asset for developers seeking to build the next generation of wayfinding applications.
Moreover, indoor routing is rarely just about finding the shortest path in terms of physical distance. It often involves finding the most accessible path for a wheelchair user, avoiding restricted employee-only zones, or taking the fastest route during a crowded time of day. Building a system capable of handling these dynamic variables requires a sophisticated routing algorithm running on top of a highly optimized spatial database framework that can update its cost metrics in real time.
2. Why Indoor Navigation is Fundamentally Different from Outdoor GPS
When you use an outdoor navigation app on your smartphone, the device calculates its position by communicating with a network of global positioning satellites. The underlying routing algorithm relies on widely available, highly standardized road network data—such as OpenStreetMap or proprietary street databases from companies like Google and TomTom. The mathematics used to calculate your path primarily deal with standardized variables: intersections, designated speed limits, turn restrictions, and live traffic conditions.
In contrast, indoor navigation completely lacks access to GPS signals, which cannot reliably penetrate roofs, concrete ceilings, and heavy structural walls. Instead, indoor positioning relies on a combination of alternative technologies such as Bluetooth Low Energy (BLE) beacons, Wi-Fi fingerprinting, magnetic field positioning, or Ultra-Wideband (UWB) tracking systems. While identifying the user's position is a separate technological challenge from generating the route itself, the routing engine must be entirely flexible so that it can integrate seamlessly with whichever hardware positioning technology the facility chooses to deploy.
Furthermore, indoor spatial data is almost never standardized. Every building is entirely unique, and its architectural blueprints are not naturally structured for routing. A typical CAD drawing or Building Information Modeling (BIM) file might perfectly show the placement of walls, windows, and doors, but it does not inherently define a "navigable network." To make indoor routing possible, GIS professionals must manually or semi-automatically convert these architectural drawings into a mathematical graph consisting of nodes (representing intersections or points of interest) and edges (representing the actual walkable paths connecting them). Creating this topological graph across multiple floors while maintaining the correct Z-elevation is one of the most critical and complex steps in the entire development process.

3. Introduction to PostGIS and pgRouting
To solve the complex topological problems associated with indoor spatial analysis, developers consistently turn to the absolute gold standard of open-source spatial database technologies: PostGIS and pgRouting. PostGIS is an advanced extension for the PostgreSQL relational database management system that adds native support for geographic objects. It allows you to store spatial data directly within standard SQL tables and query it using powerful, specialized geospatial functions such as ST_Intersects, ST_Distance, and ST_3DLength.
While PostGIS gives your database deep spatial awareness, pgRouting provides the mathematical intelligence needed to navigate efficiently through that space. pgRouting extends the PostGIS database to provide advanced geospatial routing capabilities. It contains numerous graph theory algorithms written in highly optimized C and C++, including Dijkstra's algorithm, the A-Star (A*) algorithm, the Traveling Salesperson Problem (TSP), and driving distance calculations. Because pgRouting operates directly within the database architecture, it completely eliminates the need to export massive spatial datasets over the network to an external, stand-alone routing engine. This direct integration is highly performant and allows developers to run complex, multi-variable routing queries in real-time using nothing more than standard SQL syntax.
Using PostGIS and pgRouting together enables developers to create highly dynamic routing scenarios that are impossible with static files. For example, if a specific elevator breaks down and is taken out of service, a simple SQL UPDATE statement can temporarily increase the cost of that specific elevator edge to an infinite value. This instantly recalculates all subsequent route requests to prioritize nearby stairs or alternative functioning elevators. This level of granular, dynamic control is absolutely essential for managing large facilities like hospitals, corporate campuses, and airports, where physical conditions change rapidly and unexpectedly.
4. Essential Data Requirements for Indoor Routing
Building an indoor routing network requires a heavily structured approach to spatial data modeling. At a bare minimum, your database must digitally represent the navigable pathways of a building. This is typically accomplished using a standard link-node topology. The fundamental data elements required to build this system include nodes, edges, points of interest (POIs), and building footprint metadata to group these elements together.
Nodes: Nodes represent specific geographic points in space where routing decisions are made or paths originate. This includes junctions in hallways, doorways leading into rooms, the staging areas in front of elevator bays, and the starting or ending points of staircases. Every node must possess an accurate X, Y, and Z coordinate. The Z coordinate is exceptionally critical because it represents the specific floor level, allowing the algorithm to differentiate between a hallway on the ground floor and an identical hallway stacked directly above it on the second floor.
Edges: Edges are the physical line segments that connect two nodes together. They represent the actual, walkable pathways a person can traverse. An edge might represent a long, straight hallway, a sloping ramp, a flight of stairs, or the vertical shaft of an elevator. Each edge must possess metadata attributes that define its traversal cost (most commonly, the physical length in meters) and its physical constraints (such as whether it is a one-way path, a restricted access zone, or a wheelchair accessible corridor).
Points of Interest (POIs): POIs are the actual semantic destinations that users search for—such as "Terminal 3," "Gate B12," "Cardiology Department," or "Men's Restroom." In your database schema, these POIs must be mathematically mapped or snapped to the nearest routing node on the network graph so the algorithm explicitly knows exactly where the user's journey begins or ends.
5. Digitizing and Capturing Indoor Spaces
Before you can run a single routing query, you need robust spatial data. Acquiring and formatting this data is universally recognized as the most time-consuming and labor-intensive phase of an indoor routing project. Facility managers usually provide architectural floor plans in formats like CAD (DWG) or PDF. Unfortunately, these documents are designed exclusively for construction and engineering, not for pedestrian navigation, and are notoriously cluttered with irrelevant details like plumbing schematics, electrical wiring diagrams, and structural load pillars.
To prepare this raw architectural data for a routing engine, GIS analysts use advanced desktop mapping tools like QGIS or ArcGIS to manually or semi-automatically digitize the navigable space. This tedious process involves drawing a continuous center-line network down the middle of every hallway, passing through every relevant door, and extending into every accessible room. Analysts must meticulously ensure that these lines snap together perfectly at intersections. If there is even a single millimeter gap between two connecting edges, the pgRouting algorithm will fail to bridge the gap, treating the tiny space as an impassable physical wall.
Recent technological advancements in indoor mapping, such as the use of mobile LiDAR scanners and automated BIM-to-GIS data extraction software, have significantly accelerated this digitization process. However, despite automation, rigorous human validation remains absolutely crucial to ensure that the resulting digital network accurately reflects how real human pedestrians actually move and behave within the physical space.
6. Designing the Network Schema: Nodes and Edges
Once your navigation lines are properly drawn and validated, they must be imported into the PostgreSQL database as proper spatial geometry types. A standard, production-ready routing table schema must include specific columns designed to feed the algorithms. At a minimum, you need columns for a unique identifier, source node ID, target node ID, traversal cost, reverse traversal cost, and the spatial geometry itself. Here is a detailed example of what an indoor edges table schema should look like:
- id: A primary key, unique integer for every edge in the network.
- source: An integer representing the starting node ID.
- target: An integer representing the ending node ID.
- cost: A numeric value representing the cost to traverse the edge (usually calculated as 3D length in meters, or time in seconds).
- reverse_cost: The cost to traverse the edge in the opposite direction, which is essential for modeling one-way security gates or escalators.
- level_id: An integer mapping to the specific floor number where this edge exists.
- edge_type: A descriptive text field such as 'hallway', 'stairs', 'ramp', or 'elevator'.
- is_accessible: A crucial boolean flag indicating whether a wheelchair or stroller can safely use this specific path.
- geom: The PostGIS geometry column, strictly defined as a 3D Linestring (LinestringZ).
The `source` and `target` columns are intentionally left empty when you first import your raw line data from QGIS. They are later populated automatically during the topology creation process. Structuring your database table with this exact schema ensures that the pgRouting engine has all the necessary parameters it needs to calculate the absolute most efficient path under varying real-world conditions.
7. Addressing 3D Space and Multi-Floor Routing
Indoor routing is inherently three-dimensional, presenting a massive array of unique challenges compared to flat, 2D outdoor street networks. A single large hospital or corporate building might possess a deep underground basement, an expansive ground floor, and over ten upper floors. A person moving from Floor 1 to a clinic on Floor 3 must utilize vertical transitions to breach the floor barriers—namely stairs, escalators, or elevators.
To properly handle this complex requirement in PostGIS, your network geometry must utilize the `LINESTRINGZ` data type, which naturally includes an elevation (Z) value for every vertex. When digitizing these vertical transitions, the GIS analyst draws a line that physically connects the specific node on Floor 1 to the corresponding node directly above it on Floor 3. For an elevator shaft, this line is perfectly vertical, maintaining the same X and Y coordinates while only the Z coordinate changes. For staircases, the line might zig-zag upward in a spiral pattern to accurately mimic the physical distance walked.
It is absolutely critical to assign distinct, heavily weighted routing penalties (costs) to these vertical edges. Walking 10 meters down a flat hallway takes only a few seconds, but physically climbing 10 meters of steep stairs is exhausting and takes significantly longer. Therefore, the "cost" of a stair edge should never merely equal its physical geographic length. Instead, it must be a mathematically weighted value that accurately reflects the time and physical effort required. Elevators have their own highly complex costs, heavily influenced by variable wait times, which can fluctuate wildly based on the time of day and overall building traffic.
8. Creating Network Topology with pgRouting
With your highly detailed table of 3D lines successfully imported into the database, the next critical step is to build the actual network topology. In GIS terms, topology refers to the explicit mathematical relationships between edges and nodes. The pgRouting engine requires explicit database knowledge of which edges connect to which other edges. To generate this relationship matrix, you utilize the powerful `pgr_createTopology` function built into the extension.
This function systematically analyzes your entire `geom` column and automatically identifies every location where line endpoints physically touch in 3D space. It assigns a brand new, unique ID to every discovered intersection (saving this data to a generated nodes table) and then automatically updates the empty `source` and `target` columns in your main edges table with these new node IDs. The function takes a precision tolerance parameter, which strictly tells the database exactly how close two endpoints must be geographically to be considered mathematically "touching." This strict tolerance is exactly why precision during the QGIS digitizing phase is so critically important.
After successfully running `pgr_createTopology`, your edges table is fully primed and ready for complex routing. Every single hallway segment now knows exactly which intersection node it starts at and which node it ends at, creating a mathematically perfect, continuous graph that connects every room on every floor of the entire facility.
9. Implementing Accessibility, Barriers, and Cost Metrics
True artificial intelligence in indoor routing stems from highly sophisticated cost modeling. A generated route is only as good as the parameters defining it. In a medical facility setting, a patient traveling in a wheelchair simply cannot use stairs, no matter how short the physical distance is. If your routing engine only calculates the shortest physical distance, it might recklessly direct that vulnerable patient straight to an impassable staircase.
To elegantly solve this, we rely heavily on dynamic cost calculations executed directly within the SQL query itself. If a user requests a wheelchair-accessible route on their mobile app, the backend SQL query dynamically evaluates the `is_accessible` boolean column. If `is_accessible` evaluates to false (as it naturally would for staircases and steep escalators), the query alters the edge's cost on-the-fly to an artificially high number—essentially mathematical infinity. The routing algorithm will see this infinite cost wall and immediately discard the dangerous path, searching instead for the nearest available elevator.
Similarly, certain hospital hallways might be permanently or temporarily marked as "staff only." By verifying a user's digital permission level when the routing request API is called, the SQL query can dynamically close off restricted edges by inflating their costs. This absolute control ensures that regular patients and visitors remain safely confined to public-facing corridors and lobbies.
10. Writing the Routing Queries with Dijkstra and A*
Once the spatial data is perfected and the topology is set, generating a dynamic route is as simple as running a carefully constructed SQL query. The two most widely used and reliable graph algorithms provided by the pgRouting extension are Dijkstra's algorithm (`pgr_dijkstra`) and the A-Star algorithm (`pgr_astar`).
Dijkstra’s algorithm works by methodically exploring all possible paths radiating outward from the starting node until it eventually strikes the destination node. It is mathematically guaranteed to find the absolute shortest path, but it can be computationally heavy on massive, multi-building networks because it explores blindly in all directions. The basic syntax requires passing a dynamically generated SQL string that defines the valid network, along with the source node ID and the target node ID.
The A-Star algorithm (`pgr_astar`), on the other hand, is generally heavily preferred for extremely large indoor networks. It utilizes a mathematical heuristic (estimating the remaining straight-line distance to the ultimate goal) to intelligently guide its search direction, drastically reducing unnecessary database computation time. For A-Star to function correctly, it requires the X and Y coordinates of all nodes so it can calculate this distance heuristic. Both algorithms quickly output an ordered list of edge IDs and node IDs representing the optimal path, which developers then seamlessly combine into a single, continuous geometry line string using PostGIS spatial aggregate functions like `ST_MakeLine` or `ST_Union`.
11. Real-World Use Case: Navigating a Complex Hospital Campus
Major hospitals and medical centers are notoriously difficult for the public to navigate. They are typically built in disjointed phases spanning multiple decades, resulting in labyrinthine corridors, mismatched floor levels between adjoining wings, and confusing, redundant signage. Implementing a precise indoor routing engine in a healthcare setting significantly improves the overall patient experience, reduces high anxiety levels, and directly minimizes financial losses caused by patients arriving late for critical appointments.
A hospital routing engine must prioritize several highly specific constraints. As previously discussed, wheelchair accessibility is paramount, as many patients are disabled, recovering from surgery, or pushing strollers. The entire spatial network must be meticulously tagged with accessibility metadata. Furthermore, hospitals often feature hazardous infectious disease wards or highly sterile surgical areas where public traffic must be strictly forbidden under all circumstances. The pgRouting engine must dynamically route uncredentialed visitors around these secure zones without creating confusing, illogical detours. PostGIS handles these complex constraints beautifully by allowing developers to inject conditional `CASE` statements directly into the cost parameter of the routing query.
12. Real-World Use Case: Airport Passenger Flow Management
International airports present an entirely different set of operational challenges. While physical accessibility naturally remains important, airport environments are heavily driven by time management, security protocols, and massive passenger flow bottlenecks. A stressed passenger desperately needs to know exactly how long it will actually take to walk from the initial check-in desk, physically pass through the TSA security checkpoint, and finally arrive at Gate C22 before boarding closes.
In an airport setting, the cost metric assigned to the network edges must explicitly incorporate time delays. Passing through a security checkpoint edge should inherently incur a massive time penalty representing the average current wait time, rather than just the geographic distance of the metal detectors. Additionally, many airports utilize motorized moving walkways; these specific edges should mathematically feature a significantly lower traversal cost, as passengers traverse them much faster than walking normally. PostGIS allows database administrators to link live API data feeds (such as real-time TSA wait time metrics) directly to the edges table, updating the routing costs in real-time so the engine always provides the passenger with the most accurate estimated time of arrival (ETA).
13. Integrating Indoor Routing with Web Mapping Applications
A robust spatial database that calculates mathematically perfect routes is ultimately useless without a sleek user interface to display those routes to the end user. Integrating the raw output of pgRouting into a frontend mobile or web application requires a highly efficient middleware layer and a modern JavaScript mapping library. Typically, a backend server running Node.js, Python (Django/FastAPI), or Go accepts RESTful API requests from a mobile client, executes the complex SQL routing query against the PostgreSQL database, and formats the resulting geometry into a lightweight GeoJSON payload.
On the frontend, specialized mapping libraries such as Leaflet, OpenLayers, or Mapbox GL JS seamlessly consume this GeoJSON and render the stylized route onto the user's screen over a customized base map. Because indoor maps require displaying specific floor levels stacked on top of each other, the frontend application must include intuitive floor-switching UI controls. When a user changes floors on their screen, the mapping engine instantly filters the base layers and the route segments, ensuring that only the path relevant to the currently viewed floor is visible. This dynamic visual filtering is the key to making complex 3D routes easily understandable to the average pedestrian.
14. Integrating Real-Time Positioning Systems (IPS)
To provide a true, seamless "blue dot" experience akin to what users expect from Google Maps outdoors, your indoor routing application must integrate flawlessly with an Indoor Positioning System (IPS). Bluetooth Low Energy (BLE) beacons are currently the most common and cost-effective hardware solution for this. A user's smartphone reads signal strengths from various battery-powered beacons positioned strategically around the building and calculates its own precise indoor coordinates using advanced trilateration algorithms.
When the device's IPS successfully determines the user's current X, Y, and Z coordinates, the frontend application rapidly sends this data to the PostGIS backend. A lightning-fast spatial query utilizing functions like `ST_ClosestPoint` or `ST_Distance` mathematically maps the user's raw, slightly jittery coordinate to the absolute nearest valid node on the rigid routing network. This crucial process, known in the industry as "map matching," ensures the calculated route physically originates from a logical point on the grid rather than a random coordinate stuck inside a concrete wall. As the user walks, the system continuously updates their position, automatically triggering a rapid route recalculation if it detects they have strayed too far off the previously generated path.
15. Optimizing pgRouting Performance for Large Facilities
While pgRouting is exceptionally fast right out of the box, massive facilities containing hundreds of thousands of individual edges can experience significant query lag, especially under heavy concurrent user loads during peak hours. Database performance optimization is therefore highly critical. The absolute first line of defense is proper, rigorous database indexing. Every node identifier, source column, target column, and geometry column must be heavily indexed using B-Tree and PostGIS GIST spatial indexes to ensure rapid lookups.
Another incredibly powerful optimization technique is dynamic bounding box filtering. Instead of feeding the entire sprawling hospital network into the Dijkstra or A-Star algorithm, the backend SQL query can smartly utilize the `ST_Expand` function and the `&&` spatial intersection operator to only load edges that physically fall within a specific geographic radius of the start and end points. By drastically reducing the raw number of edges the algorithm has to load into memory and evaluate, query execution times drop dramatically from hundreds of milliseconds to single digits, allowing the system backend to easily scale to handle thousands of simultaneous routing requests without crashing.
16. Maintenance, Updates, and Dynamic Routing Environments
Large buildings are emphatically not static entities. Hallways are frequently closed off for routine maintenance, entirely new medical wings are constructed, and corporate departments continuously relocate. An indoor routing engine is strictly only as good as the accuracy of its underlying spatial data. Maintaining the database requires rigorous standard operating procedures for updating the network geometry.
PostgreSQL's robust transactional nature makes it incredibly safe and easy to update the spatial network without ever causing system downtime. GIS administrators can draft major changes in an isolated staging table and seamlessly merge them into the live production network during off-hours. Furthermore, temporary physical closures—such as a spilled chemical hazard in a hallway or an out-of-order escalator—can be managed instantaneously via simple administrative API endpoints. These endpoints update the `cost` column of the affected edge to infinity, ensuring that the routing engine adapts immediately to physical changes in the facility and never sends a user into a blocked path.
17. Future Trends in Indoor GIS and Navigation
The future of indoor navigation is incredibly promising, largely driven by rapid advancements in Augmented Reality (AR) and Artificial Intelligence (AI). With sophisticated AR toolkits like Apple's ARKit and Google's ARCore, frustrated users can simply hold up their smartphone cameras to see bright digital arrows superimposed directly onto the physical hallway floor, guiding them intuitively turn-by-turn without needing to decipher a top-down 2D map.
Behind the scenes, PostGIS and pgRouting will undoubtedly continue to serve as the silent, mathematical backbone for these highly advanced visual interfaces. As AI machine learning models begin to accurately predict pedestrian traffic patterns based on historical data, routing costs will become entirely dynamic and predictive, smartly routing users away from congested corridors minutes before the physical congestion even occurs. The continued integration of IoT (Internet of Things) sensors with spatial databases will create truly "living buildings," where the digital navigation network constantly breathes, adapts, and responds to the real-time environment it represents.
18. Conclusion
Developing a highly precise indoor routing engine for large, complex facilities is a technically challenging but immensely rewarding endeavor. By deliberately moving away from highly expensive, proprietary, black-box solutions and fully embracing the open-source analytical power of PostGIS and pgRouting, developers and organizations gain absolute, uncompromised control over their spatial data and custom routing algorithms. From accurately modeling complex 3D vertical transitions to implementing highly dynamic, real-time accessibility and security constraints, the combination of these proven technologies provides all the sophisticated tools necessary to solve the intricate indoor navigation puzzle.
As the massive public need for reliable indoor wayfinding continues to grow exponentially across sprawling hospitals, massive international airports, and modern corporate campuses, mastering these specialized spatial database tools will absolutely be a defining, highly sought-after skill for modern GIS developers and software engineers alike. The fundamental blueprint is clear: digitize your floorplans meticulously, structure your network topology with extreme care, and leverage the unmatched analytical power of PostgreSQL to guide your users smoothly, safely, and efficiently to their final destinations.