Building Geofences with Bounding Box Calculations
What is a Bounding Box?
A bounding box is a rectangle defined by two coordinate pairs:
southwest corner (min_lat, min_lng) and northeast corner (max_lat, max_lng).
Any point whose latitude and longitude fall within this rectangle is "inside the fence."
Bounding boxes are a lightweight alternative to polygon geofences. They're fast to compute, easy to index, and sufficient for most use cases where a rough boundary is acceptable.
Calculating a Bounding Box
Given a centre point and a radius, the API computes the bounding box:
curl -X POST https://api.toolkitapi.io/v1/geo/bounding-box \
-H "X-API-Key: $API_KEY" \
-H "Content-Type: application/json" \
-d '{
"lat": 51.5074,
"lng": -0.1278,
"radius_km": 10
}'
{
"center": { "lat": 51.5074, "lng": -0.1278 },
"radius_km": 10,
"bbox": {
"min_lat": 51.4175,
"max_lat": 51.5973,
"min_lng": -0.2737,
"max_lng": 0.0181
}
}
Database Indexing for Fast Lookups
Store latitude and longitude as indexed columns. A bounding box query becomes a simple range filter:
SELECT * FROM locations
WHERE lat BETWEEN :min_lat AND :max_lat
AND lng BETWEEN :min_lng AND :max_lng;
Pair this with a post-filter using the Haversine formula to discard corner points outside the true circular radius.
When Bounding Boxes Are Enough
- Delivery radius checks (is this address within our service area?)
- Proximity search (find stores near me)
- Map tile selection
When to Use Polygons Instead
Complex geofences (country boundaries, irregular service zones, exclusion areas) require polygon containment tests. For those cases, use the GeoJSON polygon endpoint or a proper GIS stack.