Migrate from Google Geocoding: PHP and Python
Use GoogleGeocodeAdapter for text addresses and components, read geometry.location and understand the differences from Google Geocoding.
This adapter handles geocode only. It is not a full replacement for Google Maps, Places or the browser geocoder, and offers no reverse-geocoding adapter. Replace the server-side call and review your application’s assumptions about results.
format=google is an SDK output formatter, not a REST parameter. ApiClient removes it before sending HTTP. GoogleGeocodeAdapter selects it automatically; the third call selects it through extra with native, structured address input. The adapter returns an array/dict directly; a native SDK call returns ApiResponse, so use data() to read its formatted output.
Text parsing is best-effort: “Domaniewska 37, Warszawa” separates street, house and city, but “Domaniewska 37” without a comma becomes city in full. With commas, the last part is city, the first is street/house, and middle parts are discarded. A country suffix can therefore become the city. Only the Polish NN-NNN postal-code prefix is recognized. Prefer structured fields or components. A components string takes precedence over address, even when empty; fields are not merged. Unknown component names are ignored.
language, key, region, result_type and location_type are removed, not applied as filters or language settings. The Google key does not authenticate AutoMapa. Other top-level fields may be forwarded unchanged: send only options supported by the AutoMapa contract.
The formatter creates OK or ZERO_RESULTS from the response data. HTTP failures raise SDK exceptions before formatting; do not expect Google’s error statuses or error_message. Status and error behavior is not fully compatible with Google. place_id and geometry.viewport are null; location_type is not generated. Validate your application against representative addresses before switching providers.
Input components mapping
| components | address |
|---|---|
locality | city |
route | street |
street_number | house |
postal_code | pcode |
administrative_area_level_1 | province |
country | country |
sublocality / neighborhood | district |
Response mapping
| AutoMapa / SDK | Google-shaped output | Meaning / limitation |
|---|---|---|
x / y | geometry.location.lng / geometry.location.lat | Longitude / latitude; missing coordinates remain null. |
street, house, pcode, city, country | formatted_address | Built locally from street, house, pcode, city and country. |
country, province, city, district, pcode, street, house | address_components[] | Address fields become typed components; long_name and short_name use the same value. |
quality | types[] | types is inferred from quality: ≤2 country, 3 administrative_area_level_1, 4–5 locality, 6–7 route, ≥8 street_address. It is not Google’s accuracy classification. |
— | place_id / geometry.viewport | Always null; no Google identifier or bounds are supplied. |
raw() | _raw | The original response envelope is preserved for inspection; do not log sensitive data. |
The pinned PHP/Python geocode wrappers send top-level maxResults (Python argument max_results), which REST ignores. The Google adapter always adds maxResults=1; this does not set the server limit. Known arguments overwrite extra.address, so extra.address.maxResult does not fix the wrapper. To set the limit, call POST /v3/Geocoder/geocode directly with {"address":{"city":"Nowa Wieś","maxResult":3}}; for geocodemulti put maxResult in each address. Native examples omit the wrapper option. The SDK requires a city argument; the public REST geocoding contract also requires city in every address. For PL addresses, address.maxResult is 1–3 (default 1).
Geocoder.geocode · Geocoder.revgeocode
Read results and handle errors
An empty or null result is handled separately from an exception. NO_RESULTS is a label defined by these examples, not an API status. Catch SDK exceptions for HTTP, transport or decoding failures; SESSION_REQUIRED means your integration must provide a fresh session. The command-line entry points report a generic error without logging response bodies or sessions. Add your application’s error handling before integration.
PHP requires PHP 8.0 or later, Composer, ext-curl and ext-json. Python requires Python 3.11 or later and pip. Run the commands for your language in a terminal; the examples run on your server.
Pinned source snapshots; links point to the exact commits used by these examples.
Save the bootstrap and example files below in the SDK repository directory created during installation, using the displayed filenames. Both paths use the same bootstrap. The .txt downloads contain source code; remove .txt when saving.
PHP
automapa-map-services-php81d5014db53d5da37a121d335adc55b4c23c2818
src/Adapter/GoogleGeocodeAdapter.php
1. Install pinned sources
git clone https://github.com/automapa/automapa-map-services-php.git
cd automapa-map-services-php
git checkout --detach 81d5014db53d5da37a121d335adc55b4c23c2818
composer install --no-dev
2. Bootstrap with a supplied session
Obtain a valid AutoMapa session through your server-side authentication integration (see the authentication guide) and provide it as AUTOMAPA_SESSION_ID in the process environment. Keep it out of source control, browser code and logs. SuppliedSession below is application code implementing the SDK storage interface. Empty Config credentials are deliberate: get() throws when the supplied session is missing or cleared after HTTP 403, preventing the SDK from starting its automatic handshake. Obtain a new session through your integration and rebuild the client to retry.
bootstrap.php
Download source — bootstrap.php
<?php
declare(strict_types=1);
require_once __DIR__ . '/vendor/autoload.php';
use Automapa\MapServices\ApiClient;
use Automapa\MapServices\Config;
use Automapa\MapServices\Http\CurlHttpClient;
use Automapa\MapServices\Http\HttpClientInterface;
use Automapa\MapServices\Session\SessionManager;
use Automapa\MapServices\Session\SessionStorage;
final class SuppliedSession implements SessionStorage
{
public function __construct(private string $sessionId) {}
public function get(): ?string
{
if ($this->sessionId === '') {
throw new RuntimeException('SESSION_REQUIRED');
}
return $this->sessionId;
}
public function store(string $sessionId): void
{
$this->sessionId = $sessionId;
}
public function clear(): void
{
$this->sessionId = '';
}
}
function buildClient(string $sessionId, ?HttpClientInterface $http = null): ApiClient
{
$storage = new SuppliedSession($sessionId);
$storage->get();
$config = new Config(key: '', pass: '', baseUrl: 'https://api.automapa.com/');
$http ??= new CurlHttpClient();
return new ApiClient($config, $http, new SessionManager($config, $http, $storage));
}
3. Run the example
google-migration.php
Download source — google-migration.php
<?php
declare(strict_types=1);
require_once __DIR__ . '/bootstrap.php';
use Automapa\MapServices\ApiClient;
use Automapa\MapServices\Adapter\GoogleGeocodeAdapter;
use Automapa\MapServices\Exception\AutomapaException;
function readLocation(array $data): array
{
if (($data['status'] ?? '') === 'ZERO_RESULTS') {
return ['status' => 'NO_RESULTS'];
}
if (($data['status'] ?? '') !== 'OK') {
throw new RuntimeException('UNEXPECTED_STATUS');
}
if (empty($data['results'])) {
return ['status' => 'NO_RESULTS'];
}
$first = $data['results'][0];
$location = $first['geometry']['location'];
return ['status' => 'OK', 'lat' => $location['lat'], 'lng' => $location['lng'],
'address' => $first['formatted_address']];
}
function migrate(ApiClient $client): array
{
$adapter = new GoogleGeocodeAdapter($client);
$text = $adapter->geocode(['address' => 'Domaniewska 37, Warszawa']);
$components = $adapter->geocode([
'components' => 'locality:Warszawa|route:Domaniewska|street_number:37|country:PL',
]);
$nativeInput = $client->geocoder()->geocode(
city: 'Warszawa', street: 'Domaniewska', house: '37', country: 'PL',
extra: ['format' => 'google'],
)->data();
return array_map('readLocation', [$text, $components, $nativeInput]);
}
if (realpath($_SERVER['SCRIPT_FILENAME'] ?? '') === __FILE__) {
try {
$client = buildClient(getenv('AUTOMAPA_SESSION_ID') ?: '');
echo json_encode(migrate($client));
} catch (AutomapaException | RuntimeException | InvalidArgumentException $error) {
fwrite(STDERR, "SDK_ERROR_OR_SESSION_REQUIRED\n");
exit(1);
}
}
php google-migration.php
Python
automapa-map-services-pythonbdc98c1778d78d11a170b02dd050e89fef9247ba
automapa_map_services/adapter/google_geocode.py
1. Install pinned sources
git clone https://github.com/automapa/automapa-map-services-python.git
cd automapa-map-services-python
git checkout --detach bdc98c1778d78d11a170b02dd050e89fef9247ba
python3 -m venv .venv
. .venv/bin/activate
python -m pip install .
2. Bootstrap with a supplied session
Obtain a valid AutoMapa session through your server-side authentication integration (see the authentication guide) and provide it as AUTOMAPA_SESSION_ID in the process environment. Keep it out of source control, browser code and logs. SuppliedSession below is application code implementing the SDK storage interface. Empty Config credentials are deliberate: get() throws when the supplied session is missing or cleared after HTTP 403, preventing the SDK from starting its automatic handshake. Obtain a new session through your integration and rebuild the client to retry.
bootstrap.py
Download source — bootstrap.py
from automapa_map_services.client import ApiClient
from automapa_map_services.config import Config
from automapa_map_services.http.urllib_client import UrllibHttpClient
from automapa_map_services.session.manager import SessionManager
class SuppliedSession:
def __init__(self, session_id: str):
self.session_id = session_id
def get(self) -> str:
if not self.session_id:
raise RuntimeError("SESSION_REQUIRED")
return self.session_id
def store(self, session_id: str) -> None:
self.session_id = session_id
def clear(self) -> None:
self.session_id = ""
def build_client(session_id: str, http_client=None) -> ApiClient:
storage = SuppliedSession(session_id)
storage.get()
config = Config(key="", password="", base_url="https://api.automapa.com/")
http = http_client if http_client is not None else UrllibHttpClient()
return ApiClient(config, http, SessionManager(config, http, storage))
3. Run the example
google-migration.py
Download source — google-migration.py
import json
import os
from bootstrap import build_client
from automapa_map_services.adapter.google_geocode import GoogleGeocodeAdapter
from automapa_map_services.exceptions import AutomapaException
def read_location(data):
if data.get("status") == "ZERO_RESULTS":
return {"status": "NO_RESULTS"}
if data.get("status") != "OK":
raise RuntimeError("UNEXPECTED_STATUS")
if not data.get("results"):
return {"status": "NO_RESULTS"}
first = data["results"][0]
location = first["geometry"]["location"]
return {"status": "OK", "lat": location["lat"], "lng": location["lng"],
"address": first["formatted_address"]}
def migrate(client):
adapter = GoogleGeocodeAdapter(client)
text = adapter.geocode({"address": "Domaniewska 37, Warszawa"})
components = adapter.geocode({
"components": "locality:Warszawa|route:Domaniewska|street_number:37|country:PL"
})
native_input = client.geocoder().geocode(
city="Warszawa", street="Domaniewska", house="37", country="PL",
extra={"format": "google"},
).data()
return [read_location(data) for data in (text, components, native_input)]
if __name__ == "__main__":
try:
client = build_client(os.environ.get("AUTOMAPA_SESSION_ID", ""))
print(json.dumps(migrate(client)))
except (AutomapaException, RuntimeError, ValueError):
raise SystemExit("SDK_ERROR_OR_SESSION_REQUIRED")
python google-migration.py