Skip to main content
Server SDKs

PHP client reference

Constructor options, readonly models, and transport contracts.

All public classes are in AffordableGeoApis. Constructor and method option names use camelCase; request JSON fields use the API's field names.

GeocodingClient​

new GeocodingClient(array $options)
$client->geocode(array $request, array $options = []): GeocodingResponse
$client->search(array $request, array $options = []): GeocodingResponse
$client->reverseGeocode(array $request, array $options = []): GeocodingResponse
$client->autocomplete(array $request, array $options = []): AutocompleteResponse
$client->resolveAutocomplete(AutocompleteSuggestion $suggestion, array $options = []): GeocodingResult

Constructor options​

KeyValueDefault / requirement
baseUrlStringRequired HTTPS origin/prefix; loopback HTTP allowed
apiKeyStringRequired nonempty key without control characters
confidenceThresholdFloat or integer0.8; finite number in [0, 1]
fallbacksList of ['provider' => 'google' or 'here', 'apiKey' => string][]
fallbackOnList of trigger stringsFive default triggers
fallbackBudget['maxRequests' => int]Unlimited if omitted; nonnegative safe integer
fallbackCircuitBreaker['failureThreshold' => int, 'cooldownMs' => int]Disabled if omitted; both positive safe integers
timeoutMsInteger10000; positive, at most 2147483647
transportTransportInterfaceCurlTransport

Invalid settings raise InvalidArgumentException before network calls.

Method options​

KeyValueMeaning
signalCancellationTokenCooperative cancellation
timeoutMsPositive 32-bit integerTotal deadline for the complete provider chain

Request arrays​

Geocode requests require string street (house number and street); optional strings are city, state, zip, and country. Optional exclude_sources is a list of strings. The primary API additionally requires at least one nonempty city/state/ZIP.

Reverse requests require numeric lat and lon; optional fields are string country and list exclude_sources.

Search requests require string q (1–256 bytes); optional keys are country, near (['lat' => ..., 'lon' => ...]), limit (1–40, default 10), and exclude_sources. Invalid values throw InvalidArgumentException before networking.

For geocode and reverse, country is a routing hint not sent to primary; search also sends it as a filter. See API validation.

Models​

GeocodingResult, GeocodingResponse, and Attempt are readonly classes implementing JsonSerializable. They also expose toArray().

GeocodingResult​

String properties: id, label, type, houseNumber, street (street name only), city, state, zip, country, matchType, source, provider. Numeric properties: lat, lon, confidence. Missing text fields are ''. type is address, venue, street, zip, neighborhood, borough, city, county, state, country, or ''; matchType is primary-only (exact, interpolated, fallback).

Country is recognized uppercase ISO alpha-2 or ''. Confidence is in [0, 1], with 0 for unavailable scores. provider is primary, google, or here.

GeocodingResponse​

PropertyTypeMeaning
resultsArray of GeocodingResultSelected provider's candidates
providerStringSelected provider
fallbackReasonString or nullTrigger or unsupported_country
attemptsArray of AttemptComplete attempt history
providerResponsestdClass or nullComplete selected backup body; omitted in serialization when null

Attempt​

provider: string, outcome: string, skipReason: ?string, and error: ?GeocodingError.

Outcomes: matched, no_results, low_confidence, error, skipped. Skip reasons: budget_exhausted, circuit_open, unsupported_country. Unset skip/error fields are omitted from serialization.

Autocomplete models​

autocomplete() requires q (1–256 nonblank bytes) and a recognized country. Optional request keys are near (['lat' => ..., 'lon' => ...]), limit (1–10, default 5), exclude_sources, and sessionToken. The client generates a Google session token when omitted. AutocompleteResponse exposes readonly suggestions, provider, fallbackReason, attempts, and optional providerResponse. Each AutocompleteSuggestion has id, label, provider, and optional sessionToken. Pass that object to resolveAutocomplete() to receive one GeocodingResult. Both calls accept the usual cancellation token and timeoutMs options. Models support toArray() and JSON serialization. See address autocomplete.

Resolution returns the address directly, without an envelope, attempt history, or raw provider response. It calls only the suggestion's provider and bypasses fallback budgets/circuit breakers. An empty primary lookup throws GeocodingError with errorCode === 'provider_error'. Google/HERE must be configured on the resolving client. HTTP country is accepted only on primary autocomplete, while sessionToken remains SDK-only.

Errors and cancellation​

GeocodingError extends RuntimeException, implements JsonSerializable, and exposes readonly provider: string, errorCode: string, status: ?int, and attempts: array. Use getMessage() for text and toArray() or JSON serialization for nested errors.

String codes: http, network, timeout, invalid_response, provider_error, unsupported_country. Serialization uses code for errorCode; inherited getCode() remains numeric. Status is omitted when absent.

RequestCancelledException and RequestTimeoutException extend RuntimeException and stop the chain. They represent caller control, rather than provider errors.

CancellationToken methods: cancel(): void, isCancelled(): bool, and throwIfCancelled(): void.

Transport types​

interface TransportInterface {
public function send(HttpRequest $request, RequestContext $context): HttpResponse;
}

CurlTransport is the default implementation. It blocks the current PHP execution thread, verifies TLS certificates, and does not follow redirects.

HttpRequest is readonly, with provider: string, url: string, method: string, headers: array, body: ?string (encoded JSON), and effective per-call timeoutMs: int.

HttpResponse is readonly, with status: int, body: string, and bodyError: ?string. bodyError can be network or timeout when reading fails after headers arrive. Status must be 100–599.

RequestContext is readonly, with optional signal: ?CancellationToken and deadlineMs: ?float, measured against monotonic nowMs(): float. Methods:

  • check(): void: throw if cancelled or past the caller deadline.
  • isStopped(): bool: report cancellation or expired deadline.
  • timeoutMs(int $providerTimeoutMs): int: return the effective timeout constrained by remaining caller time.

Custom transports must honor this context and redirect restrictions. Unexpected transport exceptions become sanitized network errors. The SDK itself has no async scheduler.