Weave 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

Google Time Zone Laravel Package

spatie/google-time-zone

Convert GPS coordinates to time zone data using Google's Time Zone service. Get DST offset, raw offset, time zone ID, and time zone name from latitude and longitude. Works in plain PHP and Laravel projects, with a publishable config for your Google Maps API key and language setting.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require spatie/google-time-zone
    

    No additional configuration is required—just autoload the package.

  2. First Use Case: Fetch the timezone for a given latitude/longitude (e.g., Brussels):

    use Spatie\GoogleTimeZone\Facades\GoogleTimeZone;
    
    $timezone = GoogleTimeZone::getTimeZoneForCoordinates('51.2194475', '4.4024643');
    // Returns array with `timeZoneId`, `timeZoneName`, `rawOffset`, `dstOffset`.
    
  3. Where to Look First:


Implementation Patterns

Core Workflows

  1. Geocoding Integration: Combine with spatie/laravel-geocoder to resolve addresses → coordinates → timezones:

    $address = '1600 Amphitheatre Parkway, Mountain View, CA';
    $coordinates = Geocoder::getCoordinates($address);
    $timezone = GoogleTimeZone::getTimeZoneForCoordinates($coordinates['lat'], $coordinates['lng']);
    
  2. Model Observers: Auto-populate timezone fields on created/updated:

    // User.php
    protected static function boot()
    {
        parent::boot();
        static::created(function ($user) {
            $timezone = GoogleTimeZone::getTimeZoneForCoordinates($user->latitude, $user->longitude);
            $user->timezone_id = $timezone['timeZoneId'];
            $user->save();
        });
    }
    
  3. API Responses: Normalize timezone data for consistency:

    return response()->json([
        'timezone' => [
            'id' => $timezone['timeZoneId'],
            'name' => $timezone['timeZoneName'],
            'utc_offset' => $timezone['rawOffset'] + $timezone['dstOffset'],
        ],
    ]);
    
  4. Caching: Cache responses for static coordinates (e.g., business locations):

    $cacheKey = "timezone:{$lat}:{$lng}";
    $timezone = Cache::remember($cacheKey, now()->addHours(1), function () use ($lat, $lng) {
        return GoogleTimeZone::getTimeZoneForCoordinates($lat, $lng);
    });
    

Advanced Patterns

  • Bulk Lookups: Use Laravel’s collect() to process multiple coordinates:

    $coordinates = [['lat' => '51.2194', 'lng' => '4.4025'], ['lat' => '37.7749', 'lng' => '-122.4194']];
    $timezones = collect($coordinates)->map(fn($coord) =>
        GoogleTimeZone::getTimeZoneForCoordinates($coord['lat'], $coord['lng'])
    );
    
  • Fallback Logic: Handle invalid coordinates gracefully:

    try {
        $timezone = GoogleTimeZone::getTimeZoneForCoordinates($lat, $lng);
    } catch (\Spatie\GoogleTimeZone\Exceptions\InvalidCoordinates $e) {
        $timezone = ['timeZoneId' => 'UTC']; // Default fallback
    }
    

Gotchas and Tips

Pitfalls

  1. Rate Limits:

    • Google’s Time Zone API has usage limits (2,500 requests/day for free tier).
    • Solution: Cache aggressively or use a queue (e.g., Laravel Queues) to batch requests.
  2. Invalid Coordinates:

    • Throws InvalidCoordinates if coordinates are outside valid ranges (±90° latitude, ±180° longitude).
    • Debug Tip: Validate inputs early:
      if (!in_array($lat, range(-90, 90)) || !in_array($lng, range(-180, 180))) {
          throw new \InvalidArgumentException("Invalid coordinates");
      }
      
  3. Daylight Saving Time (DST):

    • dstOffset is 0 when DST is inactive. Always use rawOffset + dstOffset for accurate UTC offsets.
    • Example:
      $utcOffset = $timezone['rawOffset'] + $timezone['dstOffset']; // e.g., 3600 (UTC+1) or 7200 (UTC+2)
      
  4. API Key Requirements:

    • The package does not require an API key for basic usage (uses Google’s default key).
    • Warning: Google may block requests if abused. For production, add your own API key:
      GoogleTimeZone::setApiKey('YOUR_API_KEY');
      

Tips

  1. Testing:

    • Mock the facade for unit tests:
      GoogleTimeZone::shouldReceive('getTimeZoneForCoordinates')
          ->once()
          ->andReturn(['timeZoneId' => 'Europe/Paris']);
      
  2. Performance:

    • Prefer timeZoneId (e.g., Europe/Brussels) over timeZoneName for comparisons—it’s standardized and cache-friendly.
  3. Extensions:

    • Add helper methods to the facade for common use cases:
      // app/Providers/AppServiceProvider.php
      GoogleTimeZone::macro('getUtcOffset', function ($lat, $lng) {
          $timezone = $this->getTimeZoneForCoordinates($lat, $lng);
          return $timezone['rawOffset'] + $timezone['dstOffset'];
      });
      
      Usage:
      $offset = GoogleTimeZone::getUtcOffset($lat, $lng);
      
  4. Edge Cases:

    • Oceanic Coordinates: May return UTC or no timezone. Handle with fallbacks.
    • Poles: Latitude ±90 may fail. Validate or use nearest valid coordinates.
  5. Logging:

    • Log failed requests to monitor API limits:
      try {
          $timezone = GoogleTimeZone::getTimeZoneForCoordinates($lat, $lng);
      } catch (\Exception $e) {
          \Log::warning("Timezone lookup failed for {$lat},{$lng}: {$e->getMessage()}");
          throw $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.
andydefer/laravel-notification
adachsoft/cli-process-tester
jhaskell13/laraflow
sebastienheyd/boilerplate-media-manager
ccast/tagixo-primix
pretendtrue/laravel-builder
sawmainek/laravel-scout-tntsearch-driver
tomshaw/laravel-calendar-table
dibakar/laravel-ownership
steadrun/laravel-monitor
labyrinthe/connect-laravel
elmogy/layan
drewdan/sentinel-client
dskripchenko/laravel-llm
fatryst/nuonuo
stevenay/myanfont
gmostafa/php-graphql-client
xeviant/paystack
snowsoft/faker
meditationsteps/blogetc