GPS Navigation: Waypoints, Geofencing, and RTH
Position is the foundation of every autonomous behavior a drone performs. Waypoint surveys, obstacle-aware path planning, precision landing, and return-to-home all start with a receiver that turns satellite timing signals into latitude, longitude, and altitude â and with code that treats that position as uncertain rather than exact. This lesson covers how a fix is computed, how accuracy varies across receiver classes, and how to build the three navigation primitives that sit under nearly every mission: waypoint tracking, geofence enforcement, and failsafe return.
You will finish able to explain why four satellites are the minimum for a 3D fix, compare standard GPS against RTK corrections for a survey job, compute great-circle distances between waypoints, and implement a geofence point-in-polygon check with altitude limits.
How a receiver computes a fix
Every GPS satellite carries atomic clocks and broadcasts its position plus a precise transmit timestamp. The receiver measures how long each signal took to arrive, multiplies by the speed of light to get a pseudorange, and solves for position. With three satellites you can intersect three spheres to fix latitude, longitude, and altitude â except the receiver's own clock is cheap and drifted, which adds a fourth unknown. Four satellites therefore provide the minimum 3D fix: enough equations to solve for x, y, z, and clock bias simultaneously. More satellites overdetermine the solution and let the receiver least-squares out atmospheric and multipath errors.
Two error sources dominate. Ionospheric delay slows the signal in ways that vary with solar activity and are partly modeled by the broadcast message; multipath â reflections off buildings, water, and the ground â corrupts the pseudorange with no model at all, which is why urban canyons wreck accuracy. Differential corrections and sensor fusion attack different parts of this problem.
| Receiver class | Accuracy | Rate | Cost | Typical mission |
|---|---|---|---|---|
| Standard GPS | 2â5 m horizontal | 5â10 Hz | 15â50 USD | General navigation, RTH |
| Multi-band GPS | 0.5â1.5 m | 10â25 Hz | 50â150 USD | Better position hold |
| RTK with base | 1â2 cm | 10â20 Hz | 200â1000 USD | Survey, mapping, landing |
| Visual-inertial fusion | 5â20 cm drift-bounded | 30â100 Hz | 500+ USD | Indoor, GPS-denied |
RTK works by comparing the rover's carrier-phase measurements against a nearby base station that knows its own position exactly; the difference cancels most atmospheric and clock error. The catch is practical: you need a base station or a correction service with network coverage, and the fixes only hold while you remain within tens of kilometers of the reference.
Modeling missions as waypoints
A mission is an ordered list of coordinates with altitudes and actions. The essential operations are building the list, measuring its total length, and estimating duration â all of which need a proper great-circle distance rather than naive degree arithmetic, because a degree of longitude shrinks with the cosine of latitude.
import math
EARTH_RADIUS_M = 6371000.0
def haversine_m(lat1, lon1, lat2, lon2):
"""Great-circle distance in meters."""
dlat = math.radians(lat2 - lat1)
dlon = math.radians(lon2 - lon1)
a = (math.sin(dlat / 2) ** 2
+ math.cos(math.radians(lat1)) * math.cos(math.radians(lat2))
* math.sin(dlon / 2) ** 2)
return EARTH_RADIUS_M * 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))
class Mission:
def __init__(self, name="mission"):
self.name = name
self.waypoints = []
def add(self, lat, lon, alt_m, action="fly_through", speed_ms=5):
self.waypoints.append({"lat": lat, "lon": lon, "alt": alt_m,
"action": action, "speed": speed_ms})
return self
def path_length_m(self):
total = 0.0
for a, b in zip(self.waypoints, self.waypoints[1:]):
horizontal = haversine_m(a["lat"], a["lon"], b["lat"], b["lon"])
vertical = abs(b["alt"] - a["alt"])
total += math.hypot(horizontal, vertical)
return total
def estimated_seconds(self):
legs = []
for a, b in zip(self.waypoints, self.waypoints[1:]):
horizontal = haversine_m(a["lat"], a["lon"], b["lat"], b["lon"])
speed = (a["speed"] + b["speed"]) / 2
legs.append(horizontal / max(speed, 0.1))
return sum(legs)
def report(self):
print(f"{self.name}: {len(self.waypoints)} waypoints, "
f"{self.path_length_m():.0f} m, "
f"{self.estimated_seconds() / 60:.1f} min nominal")
survey = Mission("roof survey")
survey.add(37.774900, -122.419400, 10, "takeoff")
survey.add(37.774960, -122.419400, 30, "photo")
survey.add(37.774960, -122.419460, 30, "photo")
survey.add(37.774900, -122.419460, 30, "photo")
survey.add(37.774900, -122.419400, 10, "land")
survey.report()
Grid generation for mapping follows from the same primitives: convert a desired ground spacing from meters into degrees using 111,320 m per degree of latitude and that value times the cosine of latitude for longitude, then emit a serpentine pattern with overlap between passes sized to your camera's field of view.
Geofencing as a runtime constraint
A geofence is a set of boundaries the autopilot enforces independently of the pilot: maximum altitude, maximum distance from home, and exclusion polygons for airports, crowds, and property. The polygon test below is the classic ray-casting algorithm, cheap enough to run every navigation cycle.
class GeoFence:
def __init__(self, max_alt_m=120, max_radius_m=5000):
self.max_alt = max_alt_m
self.max_radius = max_radius_m
self.exclusions = []
@staticmethod
def _in_polygon(point, polygon):
x, y = point
inside = False
j = len(polygon) - 1
for i in range(len(polygon)):
xi, yi = polygon[i]
xj, yj = polygon[j]
if (yi > y) != (yj > y) and x < (xj - xi) * (y - yi) / (yj - yi) + xi:
inside = not inside
j = i
return inside
def add_exclusion(self, vertices):
self.exclusions.append(vertices)
def evaluate(self, lat, lon, alt_m, home):
violations = []
if alt_m > self.max_alt:
violations.append(f"altitude {alt_m:.0f} m above {self.max_alt} m cap")
if haversine_m(*home, lat, lon) > self.max_radius:
violations.append("beyond max distance from home")
for idx, zone in enumerate(self.exclusions):
if self._in_polygon((lat, lon), zone):
violations.append(f"inside exclusion zone {idx}")
return {"safe": not violations, "violations": violations}
fence = GeoFence(max_alt_m=100)
fence.add_exclusion([(37.7745, -122.4195), (37.7745, -122.4190),
(37.7743, -122.4190), (37.7743, -122.4195)])
home = (37.7749, -122.4194)
print(fence.evaluate(37.7744, -122.4192, 30, home))
print(fence.evaluate(37.7749, -122.4194, 150, home))
Fences must be enforced on the autopilot, not the ground station: a lost link takes the laptop out of the loop, but the flight controller keeps flying. That principle â put safety constraints as close to the actuators as possible â is the same reason failsafe behaviors are configured in firmware rather than in mission software.
Return-to-home as a state machine
RTH looks simple and hides three decisions: what altitude to climb to, when to start descending, and what to do if home itself is unsafe. The standard sequence is climb to the RTH altitude (default higher than any obstacle between the aircraft and home), fly a straight leg home, then descend vertically. Battery-triggered RTH must reserve enough energy for climb, cruise, and descent, which is why the trigger fires at 25â30 percent remaining rather than at the alarm threshold.
class ReturnToHome:
def __init__(self, home_lat, home_lon, rth_alt_m=40, reserve_pct=30):
self.home = (home_lat, home_lon)
self.rth_alt = rth_alt_m
self.reserve = reserve_pct
def plan(self, current, altitude_m, battery_pct):
steps = []
reason = "low battery" if battery_pct <= self.reserve else "operator command"
if altitude_m < self.rth_alt:
steps.append(("CLIMB", f"to {self.rth_alt} m (clear obstacles)"))
steps.append(("CRUISE", "straight leg to home at cruise speed"))
steps.append(("DESCEND", "vertical descent and landing"))
distance = haversine_m(current[0], current[1], *self.home)
return {"reason": reason, "distance_m": distance, "steps": steps}
rth = ReturnToHome(37.7749, -122.4194, rth_alt_m=50)
plan = rth.plan((37.7755, -122.4200), altitude_m=15, battery_pct=25)
print(f"RTH triggered: {plan['reason']}, {plan['distance_m']:.0f} m to home")
for phase, detail in plan["steps"]:
print(f" {phase}: {detail}")
Two failure modes deserve attention. First, an RTH altitude lower than the tallest obstacle on the path converts a failsafe into a crash â always set it from terrain knowledge, not the default. Second, GPS multipath near buildings can drag the position estimate tens of meters during descent; precision-landing workflows switch to a downward-facing camera or rangefinder for the final meter to correct it.
Putting it together: pre-flight validation
Before upload, a mission should be validated against battery energy, geofence clearance, and airspace restrictions. A single function that walks the waypoint list, sums the energy budget, and flags fence violations catches the majority of planning mistakes while they are still cheap to fix on the ground.
def validate_mission(mission, fence, home, battery_wh, cruise_watts):
minutes = battery_wh * 0.8 / cruise_watts * 60
legs_min = mission.estimated_seconds() / 60
issues = []
if legs_min * 1.3 > minutes:
issues.append("endurance insufficient with 30 percent reserve")
for wp in mission.waypoints:
check = fence.evaluate(wp["lat"], wp["lon"], wp["alt"], home)
issues.extend(check["violations"])
return {"ok": not issues, "flight_min": legs_min,
"battery_min": minutes, "issues": issues}
result = validate_mission(survey, fence, home, battery_wh=40, cruise_watts=200)
print(result)
The 1.3 safety factor accounts for wind, climb legs, and battery sag â flying a plan that only just fits the paper budget is how missions end in a field short of home.
Constellations, augmentation, and integrity
Modern receivers rarely listen to GPS alone. GLONASS, Galileo, BeiDou, and regional systems like NavIC each broadcast on related but distinct frequencies, and a multi-constellation receiver tracks satellites from several of them at once, which matters most when the sky is partly blocked â a tree line, a building wall, or the aircraft's own frame in an aggressive maneuver. More visible satellites translate directly into better geometry, measured as positional dilution of precision, and dilution is why the same receiver can report two-meter accuracy on an open field and eight-meter accuracy under a partial canopy.
Augmentation layers go further. Satellite-based augmentation systems broadcast correction envelopes that lift standard accuracy to sub-meter without any local hardware, while ground-based RTK and precise point positioning remove the remaining error for survey work. Integrity monitoring ties into failsafe logic: receivers expose fix quality, horizontal protection level, and satellite health, and an autopilot configured to require a minimum satellite count and a bounded protection level will refuse to navigate on a degraded solution rather than silently flying a thirty-meter offset as if it were truth.
Common Mistakes
Treating GPS coordinates as exact
Fix: Standard GPS wanders 2â5 m; smooth with a filter and never plan corridors narrower than the accuracy class you fly.
Leaving RTH altitude at the firmware default
Fix: Set it above the tallest obstacle on every path home, verified against terrain and obstacles before arming.
Building geofences only in mission-planning software
Fix: Enforce altitude and fence limits in the autopilot so they survive link loss and companion-computer failure.
Estimating endurance from nominal cruise power alone
Fix: Apply at least a 30 percent reserve for wind and climb; battery sag reduces usable energy further.
Best Practices
- Wait for a 3D fix with at least 10 satellites and low HDOP before arming for autonomous legs.
- Log raw GPS plus fused position during every mission to diagnose drift and multipath after the fact.
- Use RTK only where centimeter accuracy changes the outcome â survey boundaries, precision landing â otherwise multi-band GPS suffices.
- Validate every mission against battery, fence, and airspace checks before upload.
- Test RTH deliberately at safe altitude after every firmware or configuration change.
Key Takeaways
- GPS fixes require four satellites minimum â three for position plus one for receiver clock bias â with more satellites improving the solution through overdetermination.
- Accuracy classes span meters for standard receivers down to centimeters for RTK; choose based on mission tolerance, not habit.
- Waypoint missions are lists of coordinates measured with great-circle distance; grid generation converts meter spacing into degrees using latitude-dependent longitude scaling.
- Geofences must be enforced on the autopilot so they survive link loss, covering altitude caps, home radius, and exclusion polygons.
- RTH is a climb-cruise-descend state machine triggered with battery reserve; set the climb altitude from real obstacle knowledge and validate missions with a 30 percent endurance margin.