PHP code example of thinwrap / location

1. Go to this page and download the library: Download thinwrap/location 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/ */

    

thinwrap / location example snippets


use Thinwrap\Location\Enum\LocationProviderId;
use Thinwrap\Location\Config\GoogleConfig;
use Thinwrap\Location\DTO\LatLng;
use Thinwrap\Location\DTO\Routing\RoutingOptions;
use Thinwrap\Location\Routing;
use Thinwrap\Location\ConnectorError;

$routing = new Routing(LocationProviderId::Google, new GoogleConfig(apiKey: getenv('GOOGLE_KEY')));

try {
    $result = $routing->route(new RoutingOptions(
        waypoints: [
            new LatLng(40.7128, -74.0060),  // New York
            new LatLng(41.4173, -73.0001),  // Bridgeport
        ],
        travelMode: 'driving',
    ));
    echo $result->totalDistanceMeters;   // distance in meters
    echo $result->totalDurationSeconds;  // duration in seconds
    echo $result->polyline;              // Google precision-5 polyline string
} catch (ConnectorError $e) {
    error_log($e->providerCode->value . ': ' . ($e->providerMessage ?? ''));
}

use Thinwrap\Location\Config\MapboxConfig;

$a = new Routing(LocationProviderId::Google, new GoogleConfig(apiKey: getenv('GOOGLE_KEY')));
$b = new Routing(LocationProviderId::Mapbox, new MapboxConfig(accessToken: getenv('MAPBOX_TOKEN')));

$sameInput = new RoutingOptions(
    waypoints: [$origin, $destination],
    travelMode: 'driving',
);
$ra = $a->route($sameInput);
$rb = $b->route($sameInput);
// $ra and $rb share the same RoutingResult shape:
//   { legs, totalDistanceMeters, totalDurationSeconds, polyline, waypointOrder?, raw }

use GuzzleHttp\Client;
use Psr\Http\Client\ClientInterface;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;

$tracingClient = new class(new Client()) implements ClientInterface {
    public function __construct(private Client $inner) {}
    public function sendRequest(RequestInterface $req): ResponseInterface
    {
        error_log('→ ' . $req->getMethod() . ' ' . (string) $req->getUri());
        return $this->inner->sendRequest($req);
    }
};

$routing = new Routing(
    LocationProviderId::Google,
    new GoogleConfig(apiKey: getenv('GOOGLE_KEY')),
    $tracingClient,
);

use Thinwrap\Location\ConnectorError;
use Thinwrap\Location\Enum\ProviderCode;

try {
    $routing->route($input);
} catch (ConnectorError $e) {
    match ($e->providerCode) {
        ProviderCode::RateLimited           => /* respect Retry-After in $e->cause      */ null,
        ProviderCode::AuthFailed            => /* rotate credentials                     */ null,
        ProviderCode::InvalidRequest        => /* fix payload                            */ null,
        ProviderCode::InvalidRecipient      => /* fix destination                        */ null,
        ProviderCode::ProviderUnavailable   => /* transient 5xx — your retry strategy    */ null,
        ProviderCode::UnsupportedField      => /* drop OSRM-incompatible field           */ null,
        ProviderCode::UnsupportedOption     => /* drop OSRM-incompatible option          */ null,
        ProviderCode::UnsupportedTravelMode => /* fall back to a supported travel mode   */ null,
        ProviderCode::ProfileNotConfigured  => /* compile the OSRM profile               */ null,
        ProviderCode::MatrixPollingTimeout  => /* resume via $e->cause['matrixId']       */ null,
        ProviderCode::Unknown               => /* fallback                               */ null,
    };
}

use Thinwrap\Location\DTO\Passthrough;

$routing->route(new RoutingOptions(
    waypoints: [$origin, $destination],
    passthrough: new Passthrough(
        body:    ['languageCode' => 'fr', 'units' => 'IMPERIAL'],
        headers: ['X-Goog-FieldMask' => 'routes.legs.distanceMeters,routes.duration'],
        query:   ['region' => 'us'],
    ),
));

use Thinwrap\Location\Util\Polyline;

$latLngs = Polyline::decodePolyline($result->polyline);             // list<LatLng>
$re      = Polyline::encodePolyline($latLngs);                      // back to precision-5
$here    = Polyline::decodeFlexPolyline('BFoz5...');                // HERE flex-polyline
$esri    = Polyline::encodeEsriPaths([[[-74, 40], [-73.5, 40.5]]]); // ESRI paths

// Before — googlemaps/google-maps-services-php
$client = new \GoogleMaps\Client(['key' => 'YOUR_KEY']);
$response = $client->directions([...]);

// After
use Thinwrap\Location\Enum\LocationProviderId;
use Thinwrap\Location\Config\GoogleConfig;
use Thinwrap\Location\Routing;

$routing = new Routing(LocationProviderId::Google, new GoogleConfig(apiKey: 'YOUR_KEY'));
$result = $routing->route(new RoutingOptions(waypoints: [$origin, $destination]));

// Before — community Mapbox SDK
$mapbox = new \Mapbox\Mapbox(['access_token' => 'YOUR_TOKEN']);
$directions = $mapbox->directions([...]);

// After
use Thinwrap\Location\Config\MapboxConfig;

$routing = new Routing(LocationProviderId::Mapbox, new MapboxConfig(accessToken: 'YOUR_TOKEN'));
$result = $routing->route(new RoutingOptions(waypoints: [$origin, $destination]));