← All @molecule/* packages · App templates
@molecule/api-geolocationCore interface · geolocation · API (Node) · v1.0.1 · Apache-2.0
Geolocation core interface for molecule.dev — geocoding, reverse geocoding, distance calculation, autocomplete, and timezone lookups
npm install @molecule/api-geolocation@molecule/api-geolocation is the geolocation core interface on the API (Node) side: the API your app calls, with no vendor inside.
Choose the implementation by bonding one of its 3 providers: @molecule/api-geolocation-google, @molecule/api-geolocation-mapbox, @molecule/api-geolocation-nominatim.
import { setProvider, geocode, reverseGeocode, distance } from '@molecule/api-geolocation'
import { provider as google } from '@molecule/api-geolocation-google'
setProvider(google)
const results = await geocode('1600 Amphitheatre Parkway, Mountain View, CA')
const addresses = await reverseGeocode(37.4224764, -122.0842499)
const km = distance({ lat: 40.7128, lng: -74.006 }, { lat: 34.0522, lng: -118.2437 })Providers (3): @molecule/api-geolocation-google, @molecule/api-geolocation-mapbox, @molecule/api-geolocation-nominatim
Works with: @molecule/api-bond, @molecule/api-i18n
Auto-generated, AI-first package reference for the molecule.dev ecosystem. It is written to be read by coding agents as much as by people, and is generated from this package's source — edit
src/index.tsJSDoc, not this file.
Provider-agnostic geolocation interface for molecule.dev.
Defines the GeolocationProvider interface for geocoding addresses, reverse geocoding
coordinates, calculating distances, autocomplete suggestions, and timezone lookups.
Bond packages (Google Maps, Mapbox, Nominatim, etc.) implement this interface. Application
code uses the convenience functions (geocode, reverseGeocode, distance, autocomplete,
getTimezone) which delegate to the bonded provider.
import { setProvider, geocode, reverseGeocode, distance } from '@molecule/api-geolocation'
import { provider as google } from '@molecule/api-geolocation-google'
setProvider(google)
const results = await geocode('1600 Amphitheatre Parkway, Mountain View, CA')
const addresses = await reverseGeocode(37.4224764, -122.0842499)
const km = distance({ lat: 40.7128, lng: -74.006 }, { lat: 34.0522, lng: -118.2437 })
core
npm install @molecule/api-geolocation @molecule/api-bond @molecule/api-i18n
AddressComponentsStructured address components returned from geocoding operations.
interface AddressComponents {
/** Street number (e.g., `'123'`). */
streetNumber?: string
/** Street name (e.g., `'Main St'`). */
street?: string
/** City or locality name. */
city?: string
/** State or region name. */
state?: string
/** State or region abbreviation. */
stateCode?: string
/** Country name. */
country?: string
/** ISO 3166-1 alpha-2 country code (e.g., `'US'`). */
countryCode?: string
/** Postal/ZIP code. */
postalCode?: string
/** County or district. */
county?: string
/** Neighborhood or suburb. */
neighborhood?: string
}
AutocompleteOptionsOptions for autocomplete/place suggestion queries.
interface AutocompleteOptions {
/** Bias results toward this location. */
location?: LatLng
/** Radius in meters to bias results within. */
radius?: number
/** ISO 3166-1 alpha-2 country codes to restrict results to. */
countries?: string[]
/** Maximum number of results to return. */
limit?: number
/** BCP 47 language code for results (e.g., `'en'`, `'fr'`). */
language?: string
/** Session token for grouping related autocomplete requests (billing optimization). */
sessionToken?: string
}
GeolocationConfigConfiguration options for geolocation providers.
interface GeolocationConfig {
/** API key for the geolocation service. */
apiKey?: string
/** Base URL override for self-hosted or proxied services. */
baseUrl?: string
/** BCP 47 language code for results (e.g., `'en'`, `'fr'`). */
language?: string
/** ISO 3166-1 alpha-2 region code to bias results (e.g., `'US'`). */
region?: string
/** Request timeout in milliseconds. */
timeout?: number
}
GeolocationProviderGeolocation provider interface.
All geolocation providers must implement this interface. Bond packages (Google Maps, Mapbox, Nominatim, etc.) provide concrete implementations.
interface GeolocationProvider {
/**
* Converts a street address or place name to geographic coordinates.
*
* @param address - The address or place name to geocode.
* @returns An array of matching results, ordered by relevance.
*/
geocode(address: string): Promise<GeoResult[]>
/**
* Converts geographic coordinates to a human-readable address.
*
* @param lat - Latitude in decimal degrees.
* @param lng - Longitude in decimal degrees.
* @returns An array of matching address results, ordered by specificity.
*/
reverseGeocode(lat: number, lng: number): Promise<GeoResult[]>
/**
* Calculates the great-circle distance between two points using the Haversine formula.
*
* This is a pure calculation and does not require an API call.
*
* @param from - The starting coordinate.
* @param to - The ending coordinate.
* @param unit - The unit of measurement. Defaults to `'km'`.
* @returns The distance between the two points.
*/
distance(from: LatLng, to: LatLng, unit?: DistanceUnit): number
/**
* Returns place suggestions for a partial query string (typeahead).
*
* Not all providers support autocomplete. If unsupported, this method
* should return an empty array or throw with a descriptive message.
*
* @param query - The partial query string.
* @param options - Options to bias or restrict results.
* @returns An array of place suggestions.
*/
autocomplete?(query: string, options?: AutocompleteOptions): Promise<PlaceSuggestion[]>
/**
* Returns timezone information for a geographic coordinate.
*
* Not all providers support timezone lookups. If unsupported, this method
* should throw with a descriptive message.
*
* @param lat - Latitude in decimal degrees.
* @param lng - Longitude in decimal degrees.
* @returns Timezone information for the location.
*/
getTimezone?(lat: number, lng: number): Promise<TimezoneInfo>
}
GeoResultA geocoding result, mapping an address to coordinates.
interface GeoResult {
/** Latitude in decimal degrees. */
lat: number
/** Longitude in decimal degrees. */
lng: number
/** Full formatted address string. */
formattedAddress: string
/** Structured address components. */
components: AddressComponents
/** Provider-specific place identifier. */
placeId?: string
/** Bounding box of the result, if available. */
bounds?: {
/** Northeast corner. */
northeast: LatLng
/** Southwest corner. */
southwest: LatLng
}
}
LatLngA latitude/longitude coordinate pair.
interface LatLng {
/** Latitude in decimal degrees. */
lat: number
/** Longitude in decimal degrees. */
lng: number
}
PlaceSuggestionA place suggestion returned by autocomplete.
interface PlaceSuggestion {
/** Provider-specific place identifier. */
placeId: string
/** Primary text describing the place (e.g., street name). */
mainText: string
/** Secondary text describing the place (e.g., city, state). */
secondaryText: string
/** Full description of the place. */
description: string
/** Location coordinates, if available without an additional API call. */
location?: LatLng
}
TimezoneInfoTimezone information for a location.
interface TimezoneInfo {
/** IANA timezone identifier (e.g., `'America/New_York'`). */
timeZoneId: string
/** Display name of the timezone (e.g., `'Eastern Standard Time'`). */
timeZoneName: string
/** UTC offset in seconds for standard time. */
rawOffset: number
/** Additional DST offset in seconds (0 if not in DST). */
dstOffset: number
}
DistanceUnitDistance unit for calculations.
type DistanceUnit = 'km' | 'mi'
autocomplete(query, options)Returns place suggestions for a partial query string (typeahead).
function autocomplete(query: string, options?: AutocompleteOptions): Promise<PlaceSuggestion[]>
query — The partial query string.options — Options to bias or restrict results.Returns: An array of place suggestions.
distance(from, to, unit)Calculates the great-circle distance between two points using the Haversine formula.
function distance(from: LatLng, to: LatLng, unit?: DistanceUnit): number
from — The starting coordinate.to — The ending coordinate.unit — The unit of measurement. Defaults to 'km'.Returns: The distance between the two points.
geocode(address)Converts a street address or place name to geographic coordinates.
function geocode(address: string): Promise<GeoResult[]>
address — The address or place name to geocode.Returns: An array of matching results, ordered by relevance.
getProvider()Retrieves the bonded geolocation provider, throwing if none is configured.
function getProvider(): GeolocationProvider
Returns: The bonded geolocation provider.
getTimezone(lat, lng)Returns timezone information for a geographic coordinate.
function getTimezone(lat: number, lng: number): Promise<TimezoneInfo>
lat — Latitude in decimal degrees.lng — Longitude in decimal degrees.Returns: Timezone information for the location.
hasProvider()Checks whether a geolocation provider is currently bonded.
function hasProvider(): boolean
Returns: true if a geolocation provider is bonded.
reverseGeocode(lat, lng)Converts geographic coordinates to a human-readable address.
function reverseGeocode(lat: number, lng: number): Promise<GeoResult[]>
lat — Latitude in decimal degrees.lng — Longitude in decimal degrees.Returns: An array of matching address results, ordered by specificity.
setProvider(provider)Registers a geolocation provider as the active singleton. Called by bond packages during application startup.
function setProvider(provider: GeolocationProvider): void
provider — The geolocation provider implementation to bond.| Provider | Package |
|---|---|
| Geolocation | @molecule/api-geolocation-google |
| Geolocation | @molecule/api-geolocation-mapbox |
| Geolocation | @molecule/api-geolocation-nominatim |
Peer dependencies:
@molecule/api-bond ^1.0.1@molecule/api-i18n ^1.0.1@molecule/api-bond
@molecule/api-i18n
autocomplete and getTimezone are OPTIONAL provider capabilities. The
convenience wrappers THROW when the bonded provider doesn't implement them
(e.g. Mapbox and Nominatim expose no timezone API). Before building a screen
on either, confirm the chosen bond implements it — don't assume every
provider matches the fullest one's surface.
distance() still requires a bonded provider, even though it's a pure
Haversine calculation with no API call — with nothing bonded it throws the
same "no provider" error as the network methods.
Geocoding calls are metered third-party requests: debounce autocomplete input and persist geocoded coordinates alongside the stored address instead of re-geocoding on every read/render.
API keys are bond-specific config and stay SERVER-SIDE (see the bonded package's docs for its exact env var names) — never expose a geocoding key through app code; app screens call YOUR API, which calls this.
Integration checklist — drive the real UI (live preview, no mocks), adapt each item to this app's actual screens/flows, and check every box off one by one. A box you can't check is an integration bug to fix — not a skip:
geocode() returns coordinates in roughly the right place (a
famous landmark lands inside its own city, not the middle of the ocean),
and a known lat/lng passed to reverseGeocode() names the right city —
never an empty array, null, 0,0, or a hardcoded placeholder.distance() (closest first), or the address form marks a real
address valid and a bogus one invalid — a coordinate that comes back but
changes nothing in the UI is a broken integration, not a pass.geocode()/
reverseGeocode() result) surfaces a clear "location not found" message,
not a crash, a silent blank screen, or a default location shown as if real.