Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .github/workflows/provider.yml
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ jobs:
- MaxMindBinary
- Nominatim
- OpenCage
- OpenGeocoding
- OpenRouteService
- Pelias
- Photon
Expand Down
1 change: 1 addition & 0 deletions .github/workflows/subtree.yml
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,7 @@ jobs:
- { folder: MaxMindBinary, repository: maxmind-binary-provider }
- { folder: Nominatim, repository: nominatim-provider }
- { folder: OpenCage, repository: open-cage-provider }
- { folder: OpenGeocoding, repository: opengeocoding-provider }
- { folder: OpenRouteService, repository: openrouteservice-provider }
- { folder: Pelias, repository: pelias-provider }
- { folder: Photon, repository: photon-provider }
Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,7 @@ Provider | Package | Features | Stats
[MapTiler](https://github.com/geocoder-php/maptiler-provider) | `geocoder-php/maptiler-provider` | address, reverse <br> [Website](https://www.maptiler.com/cloud/geocoding/) | [![Latest Stable Version](https://poser.pugx.org/geocoder-php/maptiler-provider/v/stable)](https://packagist.org/packages/geocoder-php/maptiler-provider) <br>[![Total Downloads](https://poser.pugx.org/geocoder-php/maptiler-provider/downloads)](https://packagist.org/packages/geocoder-php/maptiler-provider)
[Nominatim](https://github.com/geocoder-php/nominatim-provider) <br> (OpenStreetMap) | `geocoder-php/nominatim-provider` | address, reverse <br> [Website](http://wiki.openstreetmap.org/wiki/Nominatim) | [![Latest Stable Version](https://poser.pugx.org/geocoder-php/nominatim-provider/v/stable)](https://packagist.org/packages/geocoder-php/nominatim-provider) <br>[![Total Downloads](https://poser.pugx.org/geocoder-php/nominatim-provider/downloads)](https://packagist.org/packages/geocoder-php/nominatim-provider)
[OpenCage](https://github.com/geocoder-php/open-cage-provider) | `geocoder-php/open-cage-provider` | address, reverse <br> [Website](https://opencagedata.com/) | [![Latest Stable Version](https://poser.pugx.org/geocoder-php/open-cage-provider/v/stable)](https://packagist.org/packages/geocoder-php/open-cage-provider) <br>[![Total Downloads](https://poser.pugx.org/geocoder-php/open-cage-provider/downloads)](https://packagist.org/packages/geocoder-php/open-cage-provider)
[OpenGeocoding](https://github.com/geocoder-php/opengeocoding-provider) | `geocoder-php/opengeocoding-provider` | address, reverse <br> [Website](https://opengeocoding.com/) | [![Latest Stable Version](https://poser.pugx.org/geocoder-php/opengeocoding-provider/v/stable)](https://packagist.org/packages/geocoder-php/opengeocoding-provider) <br>[![Total Downloads](https://poser.pugx.org/geocoder-php/opengeocoding-provider/downloads)](https://packagist.org/packages/geocoder-php/opengeocoding-provider)
[OpenRouteService](https://github.com/geocoder-php/openrouteservice-provider) | `geocoder-php/openrouteservice-provider` | address, reverse <br> [Website](https://openrouteservice.org/) | [![Latest Stable Version](https://poser.pugx.org/geocoder-php/openrouteservice-provider/v/stable)](https://packagist.org/packages/geocoder-php/openrouteservice-provider) <br>[![Total Downloads](https://poser.pugx.org/geocoder-php/openrouteservice-provider/downloads)](https://packagist.org/packages/geocoder-php/openrouteservice-provider)
[Pelias](https://github.com/geocoder-php/pelias-provider) | `geocoder-php/pelias-provider` | address, reverse <br> [Website](https://pelias.io/) | [![Latest Stable Version](https://poser.pugx.org/geocoder-php/pelias-provider/v/stable)](https://packagist.org/packages/geocoder-php/pelias-provider) <br>[![Total Downloads](https://poser.pugx.org/geocoder-php/pelias-provider/downloads)](https://packagist.org/packages/geocoder-php/pelias-provider)
[Photon](https://github.com/geocoder-php/photon-provider) | `geocoder-php/photon-provider` | address, reverse <br> [Website](https://photon.komoot.de/) | [![Latest Stable Version](https://poser.pugx.org/geocoder-php/photon-provider/v/stable)](https://packagist.org/packages/geocoder-php/photon-provider) <br>[![Total Downloads](https://poser.pugx.org/geocoder-php/photon-provider/downloads)](https://packagist.org/packages/geocoder-php/photon-provider)
Expand Down
1 change: 1 addition & 0 deletions phpunit.xml.dist
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@
<server name="MAPQUEST_API_KEY" value="YOUR_API_KEY"/>
<server name="MAPZEN_API_KEY" value="YOUR_MAPZEN_API_KEY"/>
<server name="OPENCAGE_API_KEY" value="YOUR_GEOCODING_KEY"/>
<env name="OPENGEOCODING_API_KEY" value="YOUR_API_KEY"/>
<server name="PICKPOINT_API_KEY" value="YOUR_API_KEY"/>
<server name="TOMTOM_MAP_KEY" value="YOUR_MAP_KEY"/>
<server name="GEOCODE_EARTH_API_KEY" value="YOUR_GEOCODE_EARTH_API_KEY"/>
Expand Down
5 changes: 5 additions & 0 deletions src/Provider/OpenGeocoding/.gitattributes
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
.gitattributes export-ignore
.github/ export-ignore
.gitignore export-ignore
phpunit.xml.dist export-ignore
Tests/ export-ignore
37 changes: 37 additions & 0 deletions src/Provider/OpenGeocoding/.github/workflows/provider.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
name: Provider

on:
push:
branches: [ master ]
pull_request:
branches: [ master ]

jobs:
test:
name: PHP ${{ matrix.php-version }} (${{ matrix.deps }})
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
php-version: ['8.0', '8.1', '8.2', '8.3', '8.4', '8.5']
deps: ['high']
include:
- php-version: '8.0'
deps: 'low'
steps:
- uses: actions/checkout@v7
- name: Use PHP ${{ matrix.php-version }}
uses: shivammathur/setup-php@v2
with:
php-version: ${{ matrix.php-version }}
extensions: curl
- name: Validate composer.json
run: composer validate --strict
- name: Install dependencies
if: ${{ matrix.deps == 'high' }}
run: composer update --prefer-stable --prefer-dist --no-progress
- name: Install dependencies (lowest)
if: ${{ matrix.deps == 'low' }}
run: composer update --prefer-lowest --prefer-stable --prefer-dist --no-progress
- name: Run test suite
run: composer run-script test
3 changes: 3 additions & 0 deletions src/Provider/OpenGeocoding/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
vendor/
composer.lock
phpunit.xml
9 changes: 9 additions & 0 deletions src/Provider/OpenGeocoding/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
# Change Log

The change log describes what is "Added", "Removed", "Changed" or "Fixed" between each release.

## 1.0.0

### Added

- First release: address search and reverse geocoding with the OpenGeocoding API, for PHP 8.0 to 8.5 and Geocoder PHP 4 and 5
21 changes: 21 additions & 0 deletions src/Provider/OpenGeocoding/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2026 Théo Mathieu

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
87 changes: 87 additions & 0 deletions src/Provider/OpenGeocoding/Model/OpenGeocodingAddress.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
<?php

declare(strict_types=1);

/*
* This file is part of the OpenGeocoding provider for Geocoder PHP.
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @license MIT License
*/

namespace Geocoder\Provider\OpenGeocoding\Model;

use Geocoder\Model\Address;

final class OpenGeocodingAddress extends Address
{
private ?string $displayName = null;

private bool $goodMatch = false;

private ?float $distance = null;

private ?string $layer = null;

public function getDisplayName(): ?string
{
return $this->displayName;
}

public function withDisplayName(?string $displayName): self
{
$new = clone $this;
$new->displayName = $displayName;

return $new;
}

/**
* False for a partial match, such as the street when the house number was not found.
*/
public function isGoodMatch(): bool
{
return $this->goodMatch;
}

public function withGoodMatch(bool $goodMatch): self
{
$new = clone $this;
$new->goodMatch = $goodMatch;

return $new;
}

/**
* Distance in metres from the queried point; reverse geocoding only.
*/
public function getDistance(): ?float
{
return $this->distance;
}

public function withDistance(?float $distance): self
{
$new = clone $this;
$new->distance = $distance;

return $new;
}

/**
* Reverse geocoding only: "address", "street" or "locality".
*/
public function getLayer(): ?string
{
return $this->layer;
}

public function withLayer(?string $layer): self
{
$new = clone $this;
$new->layer = $layer;

return $new;
}
}
193 changes: 193 additions & 0 deletions src/Provider/OpenGeocoding/OpenGeocoding.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,193 @@
<?php

declare(strict_types=1);

/*
* This file is part of the OpenGeocoding provider for Geocoder PHP.
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @license MIT License
*/

namespace Geocoder\Provider\OpenGeocoding;

use Geocoder\Collection;
use Geocoder\Exception\InvalidArgument;
use Geocoder\Exception\InvalidCredentials;
use Geocoder\Exception\InvalidServerResponse;
use Geocoder\Exception\QuotaExceeded;
use Geocoder\Exception\UnsupportedOperation;
use Geocoder\Http\Provider\AbstractHttpProvider;
use Geocoder\Model\AddressBuilder;
use Geocoder\Model\AddressCollection;
use Geocoder\Provider\OpenGeocoding\Model\OpenGeocodingAddress;
use Geocoder\Provider\Provider;
use Geocoder\Query\GeocodeQuery;
use Geocoder\Query\ReverseQuery;
use Psr\Http\Client\ClientInterface;

/**
* @see https://opengeocoding.com/docs
*/
final class OpenGeocoding extends AbstractHttpProvider implements Provider
{
public const API_URL = 'https://api.opengeocoding.com';

private const MAX_REVERSE_RESULTS = 10;

private string $apiKey;

public function __construct(ClientInterface $client, string $apiKey)
{
if ('' === $apiKey) {
throw new InvalidCredentials('No API key provided.');
}

$this->apiKey = $apiKey;
parent::__construct($client);
}

public function geocodeQuery(GeocodeQuery $query): Collection
{
$address = $query->getText();

if (filter_var($address, FILTER_VALIDATE_IP)) {
throw new UnsupportedOperation('The OpenGeocoding provider does not support IP addresses, only street addresses.');
}

$json = $this->executeQuery(self::API_URL.'/v1/search?'.http_build_query(['addressString' => $address]));

if ([] === $json) {
return new AddressCollection([]);
}

return new AddressCollection([$this->buildAddress($json)]);
}

public function reverseQuery(ReverseQuery $query): Collection
{
$coordinates = $query->getCoordinates();

$url = self::API_URL.'/v1/reverse?'.http_build_query([
'lat' => $coordinates->getLatitude(),
'lon' => $coordinates->getLongitude(),
'size' => max(1, min(self::MAX_REVERSE_RESULTS, $query->getLimit())),
'radiusM' => $query->getData('radiusM'),
]);

$results = [];
foreach ($this->executeQuery($url)['results'] ?? [] as $result) {
$results[] = $this->buildAddress(
$result['address'] ?? [],
isset($result['distanceM']) ? (float) $result['distanceM'] : null,
$result['layer'] ?? null
);
}

return new AddressCollection($results);
}

public function getName(): string
{
return 'opengeocoding';
}

/**
* @return array<string, mixed>
*/
private function executeQuery(string $url): array
{
$request = $this->createRequest('GET', $url, [
'Accept' => 'application/json',
'x-api-key' => $this->apiKey,
]);
$response = $this->getHttpClient()->sendRequest($request);

$status = $response->getStatusCode();
$json = json_decode((string) $response->getBody(), true);
$message = is_array($json) && isset($json['message']) && is_string($json['message']) ? $json['message'] : null;

if (401 === $status || 403 === $status) {
throw new InvalidCredentials($message ?? 'Invalid or missing API key.');
}
if (429 === $status) {
throw new QuotaExceeded($message ?? 'Rate limit or request credits exceeded.');
}
if (400 === $status && null !== $message) {
throw new InvalidArgument($message);
}
if (200 !== $status || !is_array($json)) {
throw InvalidServerResponse::create($url, $status);
}

return $json;
}

/**
* @param array<string, mixed> $item a FullAddress object
*/
private function buildAddress(array $item, ?float $distance = null, ?string $layer = null): OpenGeocodingAddress
{
$coordinates = $item['geoCoordinates'] ?? [];
$details = $item['addressDetails'] ?? [];

$builder = new AddressBuilder($this->getName());
$builder->setCoordinates((float) ($coordinates['lat'] ?? 0), (float) ($coordinates['lon'] ?? 0));
if (isset($coordinates['boundingBox'])) {
$box = $coordinates['boundingBox'];
$builder->setBounds(
(float) ($box['minLat'] ?? 0),
(float) ($box['minLon'] ?? 0),
(float) ($box['maxLat'] ?? 0),
(float) ($box['maxLon'] ?? 0)
);
}

$builder->setStreetNumber($details['houseNumber'] ?? null);
$builder->setStreetName($details['road'] ?? null);
$builder->setPostalCode($details['postcode'] ?? null);
$builder->setLocality($details['city'] ?? $details['town'] ?? $details['village'] ?? $details['hamlet'] ?? $details['municipality'] ?? null);
$builder->setSubLocality($details['suburb'] ?? $details['borough'] ?? $details['cityDistrict'] ?? $details['neighbourhood'] ?? null);
$builder->setCountry($details['country'] ?? null);
$builder->setCountryCode(isset($details['countryCode']) ? strtoupper($details['countryCode']) : null);
$this->addAdminLevels($builder, $details);

/** @var OpenGeocodingAddress $address */
$address = $builder->build(OpenGeocodingAddress::class);

return $address
->withDisplayName($item['displayName'] ?? null)
->withGoodMatch((bool) ($item['goodMatch'] ?? false))
->withDistance($distance)
->withLayer($layer);
}

/**
* @param array<string, mixed> $details an AddressDetails object
*/
private function addAdminLevels(AddressBuilder $builder, array $details): void
{
$regions = array_values(array_filter(
$details['regions'] ?? [],
fn ($region) => isset($region['enName']) || isset($region['localName'])
));
usort($regions, fn ($a, $b) => ($a['adminLevel'] ?? 0) <=> ($b['adminLevel'] ?? 0));

// Geocoder's AdminLevelCollection only accepts levels 1 to 5.
foreach (array_slice($regions, 0, 5) as $i => $region) {
$builder->addAdminLevel($i + 1, $region['enName'] ?? $region['localName'], $region['adminCode'] ?? null);
}

if ([] !== $regions) {
return;
}

$level = 1;
foreach (['state', 'county'] as $field) {
if (isset($details[$field]) && '' !== $details[$field]) {
$builder->addAdminLevel($level++, $details[$field]);
}
}
}
}
Loading
Loading