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

Tomtom Provider Laravel Package

geocoder-php/tomtom-provider

TomTom provider for the Geocoder PHP library. Adds forward and reverse geocoding via TomTom APIs, returning standardized Geocoder results for addresses, coordinates, and place lookups. Useful for Laravel/PHP apps needing TomTom-backed location search.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require geocoder-php/tomtom-provider
    

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

  2. Basic Usage

    use Geocoder\Geocoder;
    use Geocoder\Provider\TomTom\TomTomProvider;
    
    $geocoder = new Geocoder();
    $geocoder->registerProvider(new TomTomProvider('YOUR_TOMTOM_API_KEY'));
    
    // Reverse geocoding (lat/lng → address)
    $result = $geocoder->reverseQuery('52.5200', '13.4050');
    
    // Forward geocoding (address → lat/lng)
    $result = $geocoder->geocodeQuery('Berlin, Germany');
    
  3. First Use Case

    • Address Validation: Verify if a user-provided address exists and fetch coordinates.
    • Geocoding for Maps: Store lat/lng in your DB for markers (e.g., users.locations).

Implementation Patterns

Common Workflows

  1. Batch Processing Use Geocoder\Provider\MultiProvider to combine TomTom with other providers (e.g., fallback to OpenStreetMap if TomTom fails):

    $geocoder = new Geocoder();
    $geocoder->registerProvider(new TomTomProvider('API_KEY'));
    $geocoder->registerProvider(new \Geocoder\Provider\OpenStreetMap\OpenStreetMapProvider());
    
  2. Caching Responses Cache results to avoid hitting TomTom’s rate limits (e.g., 25,000 requests/day for free tier):

    $cache = new \Geocoder\Cache\DoctrineCache(new \Doctrine\Common\Cache\FilesystemCache('/path/to/cache'));
    $geocoder = new Geocoder();
    $geocoder->registerCache($cache);
    
  3. Laravel Integration Bind the geocoder to Laravel’s service container in AppServiceProvider:

    public function register()
    {
        $this->app->singleton(Geocoder::class, function ($app) {
            $geocoder = new Geocoder();
            $geocoder->registerProvider(new TomTomProvider(config('services.tomtom.key')));
            return $geocoder;
        });
    }
    

    Use in controllers:

    $address = $geocoder->geocodeQuery('1600 Amphitheatre Parkway, Mountain View');
    
  4. Error Handling Wrap queries in try-catch to handle API limits/errors:

    try {
        $result = $geocoder->reverseQuery($lat, $lng);
    } catch (\Geocoder\Exception\UnsupportedOperationException $e) {
        // Fallback logic
    }
    

Gotchas and Tips

Pitfalls

  1. API Key Management

    • Hardcoding: Never commit API keys to version control. Use Laravel’s .env or a secrets manager.
    • Rate Limits: Free tier has strict limits (25,000 requests/day). Monitor usage via TomTom’s dashboard.
    • Key Rotation: Rotate keys periodically and update your config.
  2. Response Parsing

    • TomTom returns structured JSON, but the library may not expose all fields. Access raw data via:
      $result->getData(); // Raw response array
      
    • Example: Extract countryCode from reverse geocoding:
      $address = $result->getFirstResult()->getPosition()->getCoordinates();
      $metadata = $result->getFirstResult()->getData()['address'];
      $country = $metadata['countryCode'] ?? null;
      
  3. Timeouts and Retries

    • TomTom’s API may throttle requests. Configure Guzzle’s client (used internally) for retries:
      $provider = new TomTomProvider('API_KEY', [
          'http_client' => new \GuzzleHttp\Client([
              'timeout' => 10,
              'connect_timeout' => 5,
              'allow_redirects' => false,
          ]),
      ]);
      
  4. Language/Locale Support

    • TomTom supports multiple languages. Specify in queries:
      $result = $geocoder->geocodeQuery('Pizza', [
          'language' => 'de_DE', // German
          'countrySet' => 'DE',  // Restrict to Germany
      ]);
      

Debugging Tips

  1. Enable Debug Mode Set GEOCODER_DEBUG=true in .env to log raw API responses:

    putenv('GEOCODER_DEBUG=1');
    
  2. Validate API Responses

    • Use dd($result->getData()) to inspect raw responses for unexpected formats.
    • Check TomTom’s API documentation for field mappings.
  3. Common Issues

    • 403 Forbidden: Invalid API key or IP restrictions.
    • 429 Too Many Requests: Hit rate limits. Implement exponential backoff.
    • Empty Results: Query too vague (e.g., "New York" without country). Add countrySet parameter.

Extension Points

  1. Custom Providers Extend TomTomProvider to add TomTom-specific features not exposed by the base library:

    class CustomTomTomProvider extends TomTomProvider {
        public function getTrafficInfo($lat, $lng) {
            $response = $this->httpClient->get(
                "https://api.tomtom.com/traffic/services/4/flowSegmentData/json",
                [
                    'query' => [
                        'key' => $this->apiKey,
                        'lat' => $lat,
                        'lon' => $lng,
                    ]
                ]
            );
            return json_decode($response->getBody(), true);
        }
    }
    
  2. Middleware for Requests Add headers or modify requests via the http_client option:

    $provider = new TomTomProvider('API_KEY', [
        'http_client' => new \GuzzleHttp\Client([
            'headers' => [
                'User-Agent' => 'MyApp/1.0 (contact@example.com)',
            ],
        ]),
    ]);
    
  3. Mocking for Testing Use Geocoder\Provider\MockProvider to simulate responses in tests:

    $geocoder = new Geocoder();
    $geocoder->registerProvider(new \Geocoder\Provider\MockProvider([
        '52.5200,13.4050' => 'Berlin, Germany',
    ]));
    
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.
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor