Store locations as geography points, search within a radius with ST_DWithin, sort by distance, pick the right index, and build a "near me" endpoint in Go on Encore.

"Show me what is near me" sounds like one query. With a bounding box and the haversine formula in application code, it becomes hundreds of lines that slow down as the table grows, and B-tree indexes on latitude and longitude do little for distance queries.
PostGIS handles this inside Postgres with a spatial type and a distance-aware index. This guide covers the type choice, the radius query, the index and a Go endpoint that returns the nearest places.
Use a geography(Point, 4326) column. SRID 4326 is the WGS 84 coordinate system that GPS and every map SDK use, and the geography type measures distances in meters on a spheroid, so a 5 km radius means 5 km in Oslo and in Singapore. The geometry type is faster and supports more functions, but with SRID 4326 it measures in degrees, which is not a distance anyone can reason about, so it fits best when all data is in one region and you project it to a local coordinate system.
Build points with ST_SetSRID(ST_MakePoint(lng, lat), 4326)::geography. The argument order is longitude, then latitude, the opposite of how people say coordinates out loud, and it is the most common PostGIS bug.
Filter with ST_DWithin and sort by ST_Distance:
SELECT id, name, ST_Distance(location, origin) AS meters
FROM places, (SELECT ST_SetSRID(ST_MakePoint(16.3738, 48.2082), 4326)::geography AS origin) o
WHERE ST_DWithin(location, origin, 2000)
ORDER BY meters
LIMIT 20;
ST_DWithin uses the spatial index to discard everything outside the radius before measuring, so the cost depends on how many places are nearby, not on the table size. Avoid WHERE ST_Distance(...) < 2000, which reads the same but cannot use the index and measures every row.
For "the 10 closest stores, however far away", order by the <-> distance operator with a constant origin and a LIMIT. Postgres walks the GiST index in distance order and stops after 10 rows. Combining both, a radius cap plus distance ordering, is the safer default for APIs, since an unbounded nearest search in a sparse area can return results hundreds of kilometers away that the user did not ask for.
A GiST index on the geography column:
CREATE INDEX places_location_gist ON places USING gist (location);
It serves ST_DWithin, <-> ordering and bounding-box operators. After bulk loads, run ANALYZE so the planner knows the index is selective. Managed Postgres supports this setup too, with PostGIS available on Amazon RDS and on Cloud SQL as an extension you enable per database.
Encore is a backend framework with built-in infrastructure, and the places database, its PostGIS extension and the search endpoint all live in one Go service. The Postgres database enables PostGIS in a migration, the extension ships in the Encore Postgres image used for local development, and in deployed environments Encore provisions the database on RDS or Cloud SQL in your own AWS or GCP account.
Run in your terminal to get started locally.
-- places/migrations/1_create_places.up.sql
CREATE EXTENSION IF NOT EXISTS postgis;
CREATE TABLE places (
id BIGSERIAL PRIMARY KEY,
name TEXT NOT NULL,
category TEXT NOT NULL,
location geography(Point, 4326) NOT NULL
);
CREATE INDEX places_location_gist ON places USING gist (location);
// places/places.go
package places
import (
"context"
"encore.dev/beta/errs"
"encore.dev/storage/sqldb"
)
var db = sqldb.NewDatabase("places", sqldb.DatabaseConfig{Migrations: "./migrations"})
type AddPlaceParams struct {
Name string
Category string
Lat float64
Lng float64
}
type Place struct {
ID int64
Name string
Category string
Lat float64
Lng float64
Meters float64
}
func validCoords(lat, lng float64) bool {
return lat >= -90 && lat <= 90 && lng >= -180 && lng <= 180
}
//encore:api private method=POST path=/places
func AddPlace(ctx context.Context, p *AddPlaceParams) (*Place, error) {
if !validCoords(p.Lat, p.Lng) {
return nil, &errs.Error{Code: errs.InvalidArgument, Message: "coordinates out of range"}
}
place := &Place{Name: p.Name, Category: p.Category, Lat: p.Lat, Lng: p.Lng}
err := db.QueryRow(ctx, `
INSERT INTO places (name, category, location)
VALUES ($1, $2, ST_SetSRID(ST_MakePoint($4, $3), 4326)::geography)
RETURNING id`, p.Name, p.Category, p.Lat, p.Lng).Scan(&place.ID)
if err != nil {
return nil, err
}
return place, nil
}
type NearbyParams struct {
Lat float64 `query:"lat"`
Lng float64 `query:"lng"`
RadiusM float64 `query:"radius_m"`
}
type NearbyResponse struct {
Places []*Place
}
//encore:api public method=GET path=/places/nearby
func Nearby(ctx context.Context, p *NearbyParams) (*NearbyResponse, error) {
if !validCoords(p.Lat, p.Lng) || p.RadiusM <= 0 || p.RadiusM > 50000 {
return nil, &errs.Error{Code: errs.InvalidArgument, Message: "invalid coordinates or radius (max 50 km)"}
}
rows, err := db.Query(ctx, `
SELECT id, name, category,
ST_Y(location::geometry), ST_X(location::geometry),
ST_Distance(location, o.origin) AS meters
FROM places,
(SELECT ST_SetSRID(ST_MakePoint($2, $1), 4326)::geography AS origin) o
WHERE ST_DWithin(location, o.origin, $3)
ORDER BY meters
LIMIT 20`, p.Lat, p.Lng, p.RadiusM)
if err != nil {
return nil, err
}
defer rows.Close()
resp := &NearbyResponse{}
for rows.Next() {
pl := &Place{}
if err := rows.Scan(&pl.ID, &pl.Name, &pl.Category, &pl.Lat, &pl.Lng, &pl.Meters); err != nil {
return nil, err
}
resp.Places = append(resp.Places, pl)
}
return resp, rows.Err()
}
encore run starts Postgres with PostGIS locally and applies the migration. Seed a few places, then call GET /places/nearby?lat=48.2082&lng=16.3738&radius_m=2000 and use the local trace to inspect the query time for each radius you try. The 50 km cap keeps a single request from turning into a scan of a whole country, and the API takes latitude first like every map SDK while the SQL swaps the order for ST_MakePoint.
Agents get the longitude and latitude order wrong as often as people do, and with the database running locally a test that seeds a known point in Vienna and searches for it catches the swap before review.
Best fit: Apps with stores, drivers, listings or assets on a map that want radius search in the Postgres database they already run in their own cloud account.
Store locations in a PostGIS geography(Point, 4326) column with a GiST index, then filter with ST_DWithin(location, origin, radius_in_meters) and order by ST_Distance. ST_DWithin uses the index, so the query only measures distance for rows that are already close.
Use geography for points stored as latitude and longitude when you want distances in meters across a city, country or the globe. Use geometry with a projected coordinate system when all data sits in one small region and you need the speed or the full set of spatial functions.
ST_MakePoint takes longitude first and latitude second. Passing latitude first moves a point in Vienna (48.2, 16.4) to the Indian Ocean, and every distance query against it returns nonsense.
Enable PostGIS in a migration for an Encore Postgres database, store points as geography with a GiST index, and query them from a Go endpoint with ST_DWithin. PostGIS is included in the Postgres image that encore run starts locally.
Deploy to your cloud on AWS and Google Cloud
without managing infrastructure
Encore lets developers and agents define application infrastructure directly in code, then automatically provisions it from local development to production in your AWS or GCP account.