PHP code example of andydefer / php-locationiq

1. Go to this page and download the library: Download andydefer/php-locationiq library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

andydefer / php-locationiq example snippets




declare(strict_types=1);

use AndyDefer\PhpLocationIq\Enums\LocationIqBaseUrl;
use AndyDefer\PhpLocationIq\LocationIqClient;

$client = new LocationIqClient(
    apiKey: $_ENV['LOCATIONIQ_API_KEY'],
    baseUrl: LocationIqBaseUrl::US1, // ou EU1
);



declare(strict_types=1);

use AndyDefer\PhpLocationIq\NominatimClient;
use Jenssegers\Agent\Agent;

$client = new NominatimClient(new Agent());
$client->setUserAgent('MonApp/1.0 ([email protected])');

$client->setBaseUrl(LocationIqBaseUrl::EU1);



declare(strict_types=1);

use AndyDefer\PhpLocationIq\Enums\LocationIqBaseUrl;
use AndyDefer\PhpLocationIq\LocationIqClient;

$client = new LocationIqClient(
    apiKey: $_ENV['LOCATIONIQ_API_KEY'],
    baseUrl: LocationIqBaseUrl::US1,
);

$response = $client->getBalance();

if ($response->hasError()) {
    throw new RuntimeException($response->getError());
}

echo $response->getStatus();      // 'ok'
echo $response->getDayBalance();  // 30000



declare(strict_types=1);

use AndyDefer\PhpLocationIq\Records\TimezoneRecord;
use AndyDefer\PhpVo\ValueObjects\CoordinatesVO;
use AndyDefer\PhpVo\ValueObjects\Types\FloatVO;

$response = $client->getTimezone(new TimezoneRecord(
    coordinates: new CoordinatesVO(
        FloatVO::from(19.0760),
        FloatVO::from(72.8777),
    ),
));

if ($response->hasError()) {
    throw new RuntimeException($response->getError());
}

echo $response->getName();           // 'Asia/Kolkata'
echo $response->getShortName();      // 'IST'
echo $response->getFullName();       // 'India Standard Time'
echo $response->getOffsetSeconds();  // 19800
echo $response->isInDst() ? 'DST' : 'STD';

$response = $client->getTimezone(new TimezoneRecord(
    coordinates: new CoordinatesVO(
        FloatVO::from(19.0760),
        FloatVO::from(72.8777),
    ),
    timestamp: 1609459200, // 1er janvier 2021 UTC
));



declare(strict_types=1);

use AndyDefer\PhpLocationIq\Collections\LocationVOCollection;
use AndyDefer\PhpLocationIq\Enums\DirectionsProfile;
use AndyDefer\PhpLocationIq\Enums\GeometriesType;
use AndyDefer\PhpLocationIq\Enums\OverviewType;
use AndyDefer\PhpLocationIq\Records\DirectionsRecord;
use AndyDefer\PhpLocationIq\ValueObjects\LocationVO;

$coordinates = new LocationVOCollection;
$coordinates->add(LocationVO::fromArray([15.3222, -4.3250]));
$coordinates->add(LocationVO::fromArray([15.4446, -4.3858]));

$response = $client->getDirections(new DirectionsRecord(
    coordinates: $coordinates,
    profile: DirectionsProfile::DRIVING,
    overview: OverviewType::FULL,
    steps: true,
    alternatives: false,
    geometries: GeometriesType::POLYLINE,
));

if ($response->hasError()) {
    throw new RuntimeException($response->getError());
}

foreach ($response->getRoutes() as $route) {
    printf("Distance: %.2f m, Durée: %.2f s\n", $route->distance, $route->duration);

    foreach ($route->legs as $leg) {
        foreach ($leg->steps as $step) {
            echo $step->maneuver?->type . ' — ' . $step->name . "\n";
        }
    }
}



declare(strict_types=1);

use AndyDefer\PhpLocationIq\Collections\LocationVOCollection;
use AndyDefer\PhpLocationIq\Records\MatrixRecord;
use AndyDefer\PhpLocationIq\ValueObjects\LocationVO;
use AndyDefer\PhpLocationIq\ValueObjects\MatrixOptionsVO;

$coordinates = new LocationVOCollection;
$coordinates->add(LocationVO::fromArray([-0.127627, 51.503355]));
$coordinates->add(LocationVO::fromArray([-0.087199, 51.509562]));
$coordinates->add(LocationVO::fromArray([-0.142001, 51.501284]));

$options = MatrixOptionsVO::create(coordinates: $coordinates);

$response = $client->getMatrix(new MatrixRecord(options: $options));

if ($response->hasError()) {
    throw new RuntimeException($response->getError());
}

$durations = $response->getDurations();

if ($durations !== null) {
    foreach ($durations->getRows() as $rowIndex => $row) {
        foreach ($row as $colIndex => $value) {
            if ($durations->isNoRoute($rowIndex, $colIndex)) {
                echo "[$rowIndex][$colIndex] : pas de route\n";
                continue;
            }

            echo sprintf("[%d][%d] : %.1f s\n", $rowIndex, $colIndex, $value);
        }
    }
}

use AndyDefer\PhpLocationIq\Collections\MatrixAnnotationCollection;
use AndyDefer\PhpLocationIq\Enums\MatrixAnnotation;

$annotations = new MatrixAnnotationCollection;
$annotations->add(MatrixAnnotation::DURATION);
$annotations->add(MatrixAnnotation::DISTANCE);

$options = MatrixOptionsVO::create(
    coordinates: $coordinates,
    annotations: $annotations,
);

$response = $client->getMatrix(new MatrixRecord(options: $options));

$durations = $response->getDurations(); // secondes
$distances = $response->getDistances(); // mètres

use AndyDefer\DomainStructures\Collections\Utility\IntTypedCollection;

$sources = new IntTypedCollection;
$sources->add(0);      // utilise uniquement la coordonnée #0 comme source

$options = MatrixOptionsVO::create(
    coordinates: $coordinates,
    sources: $sources,
);

// Résultat : matrice 1×3 au lieu de 3×3

use AndyDefer\PhpLocationIq\Enums\FallbackCoordinate;

$options = MatrixOptionsVO::create(
    coordinates: $coordinates,
    fallbackSpeed: 15.5,                                // 15.5 m/s ≈ 56 km/h
    fallbackCoordinate: FallbackCoordinate::SNAPPED,    // utilise la coordonnée snappée
);

$durations = $response->getDurations();

if ($durations !== null) {
    $value = $durations->getCell(0, 1);          // float ou NO_ROUTE_SENTINEL (-1.0)
    $noRoute = $durations->isNoRoute(0, 1);      // bool
}



declare(strict_types=1);

use AndyDefer\PhpLocationIq\NominatimClient;
use AndyDefer\PhpLocationIq\Records\Nominatim\ReverseRecord;
use AndyDefer\PhpVo\ValueObjects\CoordinatesVO;
use AndyDefer\PhpVo\ValueObjects\Types\FloatVO;
use Jenssegers\Agent\Agent;

$client = new NominatimClient(new Agent());
$client->setUserAgent('MonApp/1.0 ([email protected])');

$response = $client->reverse(new ReverseRecord(
    coordinates: new CoordinatesVO(
        FloatVO::from(-4.3617),
        FloatVO::from(15.2183),
    ),
));

if ($response->hasError()) {
    throw new RuntimeException($response->getError());
}

echo $response->getDisplayName() . "\n";
// 'Kasi, Lukunga, Ngaliema, Kinshasa, République démocratique du Congo'

$address = $response->getAddress();

if ($address !== null) {
    echo $address->cityDistrict . "\n";  // 'Kasi'
    echo $address->municipality . "\n";  // 'Ngaliema'
    echo $address->state . "\n";         // 'Kinshasa'
    echo $address->country . "\n";       // 'République démocratique du Congo'
    echo $address->countryCode . "\n";   // 'cd'
}

use AndyDefer\PhpLocationIq\ValueObjects\LocationVO;
use AndyDefer\PhpLocationIq\ValueObjects\BoundingBoxVO;

$location = LocationVO::fromArray([15.3222, -4.3250]);

echo $location->getLongitude(); // 15.3222
echo $location->getLatitude();  // -4.325
echo (string) $location;        // "15.322200,-4.325000"

$bbox = BoundingBoxVO::fromArray([-4.3631, -4.3619, 15.2171, 15.2186]);

echo $bbox->getMinLatitude();  // -4.3631
echo $bbox->getMaxLatitude();  // -4.3619
echo $bbox->getMinLongitude(); // 15.2171
echo $bbox->getMaxLongitude(); // 15.2186

$response = $client->getDirections($record);

if ($response->hasError()) {
    echo $response->getError(); // 'InvalidOptions'
}

$response = $client->getMatrix($matrixRecord);

if ($response->hasError()) {
    echo $response->getError(); // 'NoTable' ou 'NotImplemented'
}

usleep(1_100_000); // 1,1 seconde



declare(strict_types=1);

namespace App\Providers;

use AndyDefer\PhpLocationIq\Contracts\LocationIqClientInterface;
use AndyDefer\PhpLocationIq\Contracts\NominatimClientInterface;
use AndyDefer\PhpLocationIq\Enums\LocationIqBaseUrl;
use AndyDefer\PhpLocationIq\LocationIqClient;
use AndyDefer\PhpLocationIq\NominatimClient;
use Illuminate\Support\ServiceProvider;
use Jenssegers\Agent\Agent;

final class GeoServiceProvider extends ServiceProvider
{
    public function register(): void
    {
        $this->app->singleton(LocationIqClientInterface::class, function () {
            return new LocationIqClient(
                apiKey: config('geo.locationiq.api_key'),
                baseUrl: config('geo.locationiq.base_url') === 'eu1'
                    ? LocationIqBaseUrl::EU1
                    : LocationIqBaseUrl::US1,
            );
        });

        $this->app->singleton(NominatimClientInterface::class, function () {
            $client = new NominatimClient(new Agent());

            if ($userAgent = config('geo.nominatim.user_agent')) {
                $client->setUserAgent($userAgent);
            }

            return $client;
        });
    }
}



// config/geo.php

return [
    'locationiq' => [
        'api_key' => env('LOCATIONIQ_API_KEY'),
        'base_url' => env('LOCATIONIQ_BASE_URL', 'us1'),
    ],
    'nominatim' => [
        'user_agent' => env('NOMINATIM_USER_AGENT'),
    ],
];



declare(strict_types=1);

namespace App\Http\Controllers;

use AndyDefer\PhpLocationIq\Contracts\LocationIqClientInterface;
use AndyDefer\PhpLocationIq\Contracts\NominatimClientInterface;
use AndyDefer\PhpLocationIq\Collections\LocationVOCollection;
use AndyDefer\PhpLocationIq\Records\DirectionsRecord;
use AndyDefer\PhpLocationIq\Records\Nominatim\ReverseRecord;
use AndyDefer\PhpLocationIq\ValueObjects\LocationVO;
use AndyDefer\PhpVo\ValueObjects\CoordinatesVO;
use AndyDefer\PhpVo\ValueObjects\Types\FloatVO;
use Illuminate\Http\JsonResponse;

final class GeoController
{
    public function __construct(
        private readonly LocationIqClientInterface $locationiq,
        private readonly NominatimClientInterface $nominatim,
    ) {}

    public function route(Request $request): JsonResponse
    {
        $coordinates = new LocationVOCollection;
        $coordinates->add(LocationVO::fromArray([$request->from_lon, $request->from_lat]));
        $coordinates->add(LocationVO::fromArray([$request->to_lon, $request->to_lat]));

        $response = $this->locationiq->getDirections(
            new DirectionsRecord(coordinates: $coordinates),
        );

        if ($response->hasError()) {
            return response()->json(['error' => $response->getError()], 422);
        }

        return response()->json(['routes' => $response->getRoutes()->toArray()]);
    }

    public function reverse(Request $request): JsonResponse
    {
        $response = $this->nominatim->reverse(new ReverseRecord(
            coordinates: new CoordinatesVO(
                FloatVO::from((float) $request->lat),
                FloatVO::from((float) $request->lon),
            ),
        ));

        if ($response->hasError()) {
            return response()->json(['error' => $response->getError()], 422);
        }

        return response()->json(['address' => $response->getData()->reverse?->address?->toArray()]);
    }
}
bash
composer