geofencing

Pure-Python geofencing for GPS, IoT and fleet telematics: point-in-polygon, circle and corridor fences, an R-tree index and enter/exit/dwell events with hysteresis, schedules and speed zones.

Version 0.1.2 · Python >=3.9 · MIT licence
pip install geofencing
PyPISourceIssuesChangelogCite (DOI)

geofencing

PyPI version Python versions pipeline status License: MIT DOI Downloads

Fast, dependency-free geofencing for Python. Check which fences contain a point, index tens of thousands of fences, and turn streams of GPS fixes into ENTER / EXIT / DWELL events that do not flap when a vehicle sits on a boundary.

Built for IoT, fleet, telematics and mobility back ends:

pip install geofencing            # stdlib only
pip install "geofencing[numpy]"   # vectorised batch checks
pip install "geofencing[tz]"      # IANA timezone data (needed on Windows)

Python 3.9 to 3.13.

Quick start

from geofencing import CircleFence, CorridorFence, FenceIndex, GeofenceEngine, PolygonFence

fences = [
    CircleFence("depot", 29.020, 41.010, radius_m=150, speed_limit=20),
    PolygonFence.from_polygon(
        "school-zone",
        [[29.030, 41.010], [29.036, 41.010], [29.036, 41.014], [29.030, 41.014], [29.030, 41.010]],
        speed_limit=30,
        schedule={"timezone": "Europe/Istanbul", "rules": ["Mon-Fri 07:00-09:00"]},
    ),
    CorridorFence("main-road", [[[29.01, 41.012], [29.05, 41.012]]], radius_m=30, speed_limit=50),
]
index = FenceIndex(fences)

index.containing_ids(29.0201, 41.0101)                                # ['depot']
index.speed_limit_at(29.033, 41.012, "2026-11-09T07:30:00+03:00")     # 30.0 (school in session)
index.speed_limit_at(29.033, 41.012, "2026-11-09T12:00:00+03:00")     # 50.0 (road only)

engine = GeofenceEngine(
    index,
    min_inside_s=10,     # ENTER only after 10 s inside
    min_outside_s=10,    # EXIT only after 10 s outside
    buffer_m=10,         # fixes within 10 m of a boundary are "uncertain"
    dwell_s=300,         # DWELL after 5 minutes inside
    max_accuracy_m=50,   # fixes reported worse than 50 m ...
    poor_accuracy="ignore",
)
engine.subscribe(lambda ev: print(ev.type, ev.fence_id), types=["enter", "exit"])

for event in engine.process_many(positions):   # Position objects or dicts
    send_to_queue(event.to_dict())

A position is Position(device_id, lon, lat, t, accuracy=None, speed=None) with t in POSIX seconds, or a dict with the same keys (t may be an ISO 8601 string).

Fences

Class Geometry Notes
PolygonFence(id, polygons) GeoJSON MultiPolygon coordinates; PolygonFence.from_polygon(id, exterior, holes) for one polygon Edges are straight in lon/lat (RFC 7946). Any orientation; holes; concave and self-touching rings.
CircleFence(id, lon, lat, radius_m) geodesic circle on WGS84 A spherical distance settles clear cases; points within 1 % of the radius are re-measured with Vincenty on the ellipsoid.
CorridorFence(id, lines, radius_m) buffered polyline(s) radius_m is the half-width. Great-circle segments on the mean sphere.
BBoxFence(id, west, south, east, north) lon/lat box west > east crosses the antimeridian.

Every fence takes the same keyword arguments: name, properties, schedule, speed_limit, boundary="inclusive" | "exclusive" and tolerance_m.

fence.contains(lon, lat, t=None, inclusive=None, tolerance_m=None)  # -> bool
fence.locate(lon, lat, margin_m=0)    # 1 inside, 0 within margin of the boundary, -1 outside
fence.signed_distance(lon, lat)       # metres to the boundary, positive inside
fence.contains_many(lons, lats)       # vectorised with NumPy, plain loop without

The antimeridian and the poles

Boundaries and tolerance

boundary="inclusive" (default) treats points on an edge or vertex as inside. tolerance_m widens "on the boundary" to a band in metres (measured in a local equirectangular frame around the point), which is handy for snapping noisy fixes or for fences digitised with limited precision. Exact on-edge detection uses exact arithmetic on the input coordinates, so vertices are always boundary points.

Spatial index

FenceIndex holds any number of fences behind an STR-packed R-tree (geofencing.STRTree, also usable on its own). Building the tree for 10^5 fences takes about 0.5 s; fences can be added or removed (the tree is rebuilt lazily).

index.candidates(lon, lat, margin_m=0)          # bounding-box hits
index.containing(lon, lat, t=None)              # exact hits, schedules applied when t is given
index.speed_limit_at(lon, lat, t=None)          # lowest limit of the containing fences
index.contains_many(lons, lats, t=None)         # list of fence-id lists, vectorised with NumPy

Event engine

For each device and fence:

OUTSIDE --inside fix--> PENDING_ENTER --inside >= min_inside_s--> INSIDE      (ENTER)
INSIDE --outside fix--> PENDING_EXIT  --outside >= min_outside_s--> OUTSIDE   (EXIT)
INSIDE --inside >= dwell_s (and every dwell_repeat_s)-->                      (DWELL)
async for event in engine.astream(mqtt_positions()):
    await publish(event.to_dict())

GeoJSON, CSV and JSONL

from geofencing import load_fences, save_fences, read_positions, write_events

fences = load_fences("fences.geojson")
events = engine.process_many(read_positions("positions.csv"))
write_events(events, "events.jsonl")

GeoJSON features map to fences as follows:

Geometry Properties Fence
Polygon, MultiPolygon PolygonFence
Point radius_m CircleFence
LineString, MultiLineString radius_m / buffer_m (half-width) or width_m CorridorFence
any or none "fence_type": "bbox", "bbox": [w, s, e, n] BBoxFence

Optional properties: id (or the feature id), name, speed_limit (alias maxspeed), boundary, tolerance_m and schedule, for example {"timezone": "Europe/Istanbul", "rules": ["Mon-Fri 07:00-09:00", {"days": "Sat", "start": "22:00", "end": "06:00"}]}. Timezones are UTC, fixed offsets such as +03:00, or IANA names (install the tz extra on Windows).

Position files are CSV or JSONL with case-insensitive column names: device_id/device/vehicle_id, lon/lng/longitude, lat/latitude, t/time/timestamp (POSIX seconds or ISO 8601), optional accuracy and speed.

Command line

geofencing check fences.geojson --lat 41.0101 --lon 29.0201
# {"lon": 29.0201, "lat": 41.0101, "inside": ["depot"], "speed_limit": 20.0}

geofencing replay fences.geojson positions.csv -o events.jsonl \
    --min-inside 10 --min-outside 10 --buffer 10 --dwell 300 \
    --max-accuracy 50 --state-out state.json

geofencing bench --fences 10000 --points 50000

check also takes --time, --tolerance, --exclusive and --exit-code; replay takes every engine option plus --state-in to resume. The examples/ folder has demo fences, a synthetic track and quickstart.py.

Correctness

The test suite (pytest) checks:

Performance

geofencing bench on one core of an AMD Ryzen laptop CPU (Python 3.12, Windows), 50,000 random points. Synthetic fences are 75 % concave 24-vertex polygons and 25 % circles of 100-800 m, scattered at 10^4 fences per 85 x 55 km.

Fences Method Points / s
1 (256-vertex concave polygon) fence.contains 262,000
1 (256-vertex concave polygon) index.containing 188,000
1 (256-vertex concave polygon) index.contains_many (NumPy) 1,160,000
10,000 index.containing 37,000
10,000 index.contains_many (NumPy) 61,000
10,000 engine.process (100 devices, hysteresis on) 25,000
100,000 index.containing 21,000
100,000 engine.process (100 devices, hysteresis on) 17,000

Building the R-tree takes 0.04 s for 10^4 fences and 0.5 s for 10^5 (depth 4 and 5). Run geofencing bench to measure your own hardware.

Development

git clone https://gitlab.com/geophilo1/geofencing_sdk.git
cd geofencing_sdk
pip install -e ".[dev]"
pytest --cov=geofencing
ruff check . && ruff format --check src tests && mypy src

Coverage is about 99 % with the optional packages installed; the suite also runs with the standard library alone (Shapely, pyproj and NumPy tests are skipped).

Related Geophilo SDKs

License

MIT (c) Yusuf Eminoğlu. See LICENSE and CITATION.cff.

Academic citation

@software{eminoglu_geofencing,
  author  = {Eminoğlu, Yusuf},
  title   = {geofencing},
  year    = {2026},
  version = {0.1.2},
  doi     = {10.5281/zenodo.24065190},
  url     = {https://doi.org/10.5281/zenodo.24065190}
}

See also CITATION.cff.

Other Geophilo SDKs