Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Openrouteservice Provider Laravel Package

geocoder-php/openrouteservice-provider

OpenRouteService provider for Geocoder PHP. Integrates ORS geocoding into the Geocoder ecosystem via a simple provider class, supporting forward and reverse geocoding through the OpenRouteService API with configurable HTTP client and API key.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require geocoder-php/openrouteservice-provider
    

    Ensure geocoder-php/geocoder is also installed (core dependency).

  2. Basic Configuration Add the provider to your Geocoder client:

    use Geocoder\ProviderManager;
    use GeocoderPhp\OpenrouteserviceProvider;
    
    $provider = new OpenrouteserviceProvider('YOUR_OPENROUTE_SERVICE_API_KEY');
    $client = new ProviderManager();
    $client->addProvider('openrouteservice', $provider);
    
  3. First Use Case: Geocoding

    $geocode = $client->geocodeQuery('Berlin, Germany');
    foreach ($geocode as $hit) {
        echo $hit->getCoordinates(); // Output: [longitude, latitude]
    }
    
  4. First Use Case: Routing

    $route = $client->route([
        'coordinates' => [[13.404954, 52.520008], [13.388860, 52.517037]],
        'profile' => 'driving-car'
    ]);
    

Where to Look First


Implementation Patterns

Common Workflows

1. Geocoding Addresses

$results = $client->geocodeQuery('1600 Amphitheatre Parkway, Mountain View, CA');
$firstResult = $results->first();
$coordinates = $firstResult->getCoordinates();
$formattedAddress = $firstResult->getFormattedAddress();

2. Reverse Geocoding

$reverse = $client->reverseQuery([13.404954, 52.520008]);
foreach ($reverse as $hit) {
    echo $hit->getStreetNumber() . ' ' . $hit->getStreetName();
}

3. Routing with Custom Profiles

$route = $client->route([
    'coordinates' => [[lon1, lat1], [lon2, lat2]],
    'profile' => 'cycling-regular', // Other options: 'foot-walking', 'driving-hgv'
    'options' => ['elevation' => true] // Additional OpenRouteService options
]);

4. Batch Processing

$addresses = ['Berlin', 'Paris', 'Tokyo'];
$results = $client->geocodeBatch($addresses);

5. Integration with Laravel

// In a service provider or config file
$client = new ProviderManager();
$client->addProvider('openrouteservice', new OpenrouteserviceProvider(config('services.openrouteservice.key')));

// Bind to Laravel container
app()->singleton('geocoder', function () use ($client) {
    return $client;
});

Then inject geocoder into controllers/services:

public function __construct(private ProviderManager $geocoder) {}

Integration Tips

Caching Responses

Use Laravel's cache to avoid hitting API limits:

$cacheKey = 'geocode_' . md5($query);
$results = Cache::remember($cacheKey, now()->addHours(1), function () use ($client, $query) {
    return $client->geocodeQuery($query);
});

Error Handling

Wrap calls in try-catch:

try {
    $route = $client->route($coordinates);
} catch (\Geocoder\Exception\UnsupportedProviderException $e) {
    Log::error('OpenRouteService provider error: ' . $e->getMessage());
    // Fallback to another provider
}

Rate Limiting

OpenRouteService has rate limits. Implement exponential backoff:

use Symfony\Component\RateLimiter\RateLimiter;

$rateLimiter = new RateLimiter(10, 'minute'); // 10 requests/minute
if (!$rateLimiter->isAllowed()) {
    sleep($rateLimiter->getWaitTime());
}

Environment Configuration

Store API keys in .env:

OPENROUTESERVICE_KEY=your_api_key_here

Then load in config/services.php:

'openrouteservice' => [
    'key' => env('OPENROUTESERVICE_KEY'),
],

Gotchas and Tips

Pitfalls

1. API Key Leaks

  • Gotcha: Hardcoding API keys in code or committing them to version control.
  • Fix: Use Laravel's .env and config/services.php. Add .env to .gitignore.

2. Rate Limit Exceeded

  • Gotcha: Hitting the OpenRouteService rate limits (e.g., 100 requests/minute for free tier).
  • Fix:
    • Implement caching (as shown above).
    • Use the options['timeout'] parameter to avoid hanging:
      $client->route([...], ['timeout' => 5]); // 5-second timeout
      
    • Monitor usage via OpenRouteService dashboard.

3. Coordinate Order

  • Gotcha: OpenRouteService expects [longitude, latitude] (not [latitude, longitude]).
  • Fix: Always ensure coordinates are in the correct order:
    $coordinates = [13.404954, 52.520008]; // Correct: [lon, lat]
    

4. Profile Availability

  • Gotcha: Not all profiles are available for all endpoints. For example, driving-hgv may not support elevation.
  • Fix: Check OpenRouteService profiles before use.

5. Deprecated Methods

  • Gotcha: The package may lag behind OpenRouteService API updates.
  • Fix: Check the OpenRouteService changelog and update the provider manually if needed.

Debugging Tips

1. Enable Debugging

$provider->setDebug(true); // Enable HTTP request logging

Logs will show the raw API response for troubleshooting.

2. Validate API Responses

OpenRouteService returns structured JSON. Validate responses:

$route = $client->route($coordinates);
if (isset($route['routes'][0]['geometry'])) {
    // Success
} else {
    // Handle error (e.g., invalid coordinates)
}

3. Check HTTP Status Codes

Wrap the provider in a custom class to log HTTP errors:

use GuzzleHttp\Exception\RequestException;

$provider->setHttpClient(new \GuzzleHttp\Client([
    'on_request' => function ($request) {
        Log::debug('OpenRouteService Request:', [
            'method' => $request->getMethod(),
            'uri' => (string) $request->getUri(),
        ]);
    },
    'on_response' => function ($response) {
        Log::debug('OpenRouteService Response:', [
            'status' => $response->getStatusCode(),
            'body' => (string) $response->getBody(),
        ]);
    },
    'on_error' => function (RequestException $e) {
        Log::error('OpenRouteService Error:', [
            'message' => $e->getMessage(),
            'response' => $e->getResponse() ? (string) $e->getResponse()->getBody() : null,
        ]);
    },
]));

Extension Points

1. Custom HTTP Client

Override the default Guzzle client for retries, middleware, or proxies:

$client = new \GuzzleHttp\Client([
    'timeout' => 10,
    'headers' => [
        'Accept' => 'application/json',
        'User-Agent' => 'MyApp/1.0',
    ],
]);
$provider->setHttpClient($client);

2. Add Headers

Include custom headers (e

Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium