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

Google Map Laravel Package

arcasolutions/google-map

Laravel package providing Google Maps integration for your app, with helpers to generate map views and include the required scripts. Useful for quickly embedding maps and configuring markers or map options within Laravel projects.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the package via Composer:

    composer require arcasolutions/google-map
    

    Requires PHP 5.6 (note: Laravel 5.6+ is compatible but may need polyfills for older PHP features).

  2. Basic Usage Initialize the client with your API key (from Google Cloud Console):

    use ArcaSolutions\GoogleMap\GoogleMap;
    
    $client = new GoogleMap('YOUR_API_KEY');
    
  3. First Use Case: Embedding a Map Generate a simple map with markers:

    $map = $client->map()
        ->center(40.7128, -74.0060) // New York coordinates
        ->zoom(12)
        ->addMarker('Times Square', 40.7580, -73.9855);
    
    echo $map->getHtml();
    
  4. Where to Look First

    • Documentation: Check the GitHub repo (if available) or inspect src/GoogleMap.php for methods.
    • Examples: Look for tests/ or examples/ directories (if present).
    • Laravel Integration: Override the default client in config/services.php or bind it in a service provider:
      $this->app->singleton('google-map', function ($app) {
          return new GoogleMap(config('services.google-map.key'));
      });
      

Implementation Patterns

Common Workflows

1. Dynamic Map Generation in Controllers

Use dependency injection to fetch the client:

public function showMap(GoogleMap $googleMap) {
    $map = $googleMap->map()
        ->center(request('lat'), request('lng'))
        ->zoom(14)
        ->addMarker('User Location', request('lat'), request('lng'));

    return view('maps.show', ['map' => $map->getHtml()]);
}

2. Reusable Map Components (Blade)

Create a Blade component for consistency:

// resources/views/components/google-map.blade.php
<div class="map-container">
    {!! $map !!}
</div>

Usage:

@component('components.google-map', ['map' => $map->getHtml()])
@endcomponent

3. Geocoding Addresses

Convert addresses to coordinates:

$geocode = $client->geocode('1600 Amphitheatre Parkway, Mountain View, CA');
if ($geocode->success()) {
    $lat = $geocode->getLat();
    $lng = $geocode->getLng();
}

4. Directions API

Calculate routes between points:

$directions = $client->directions()
    ->origin('New York, NY')
    ->destination('Los Angeles, CA')
    ->get();

if ($directions->success()) {
    $polyline = $directions->getPolyline();
    // Render polyline on map
}

5. Caching Responses

Cache API responses to reduce calls (e.g., geocoding):

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

Integration Tips

Laravel Service Provider Binding

Bind the client with configuration:

$this->app->bind('google-map', function ($app) {
    return new GoogleMap(config('services.google-map.key'));
});

API Key Management

Store the API key in .env:

GOOGLE_MAP_API_KEY=your_key_here

Load it in config/services.php:

'google-map' => [
    'key' => env('GOOGLE_MAP_API_KEY'),
],

Handling API Limits

Implement retry logic for quota limits (e.g., using spatie/laravel-queueable):

try {
    $response = $client->geocode($address);
} catch (GoogleMapException $e) {
    if ($e->getCode() === 403) { // Quota exceeded
        return back()->withError('Retry later.');
    }
}

Extending the Package

Create a decorator for custom logic:

class CustomGoogleMap extends GoogleMap {
    public function addCustomMarker($title, $lat, $lng, $icon = null) {
        $marker = $this->addMarker($title, $lat, $lng);
        if ($icon) {
            $marker->setIcon($icon);
        }
        return $marker;
    }
}

Gotchas and Tips

Pitfalls

1. Deprecated PHP Features

  • The package targets PHP 5.6, which may conflict with Laravel 5.6+ features (e.g., type hints, namespaces).
  • Fix: Use a polyfill like php-compat or upgrade the package (if possible).

2. No Laravel-Specific Features

  • Lacks built-in support for:
    • Queueing API calls.
    • Eloquent model bindings.
    • Blade directives.
  • Workaround: Wrap the package in a Laravel facade or service class.

3. Outdated API Methods

  • Google Maps API v3 has evolved since 2016. Some methods may be deprecated or require updates.
  • Tip: Check the Google Maps API changelog and override methods if needed.

4. No Built-in Error Handling

  • The package throws generic exceptions. Extend it for Laravel-specific errors:
    catch (GoogleMapException $e) {
        throw new \Exception("Google Maps API Error: {$e->getMessage()}", $e->getCode());
    }
    

5. Hardcoded Library URLs

  • The package may use hardcoded URLs for Google Maps JS/CSS. Override them in your layout:
    <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_KEY"></script>
    

Debugging Tips

1. Enable API Debugging

Add query parameters to Google Maps URLs for debugging:

$map->setLibrary('places,geometry'); // Enable additional libraries
$map->setDebug(true); // If supported (check package docs)

2. Log API Responses

Extend the client to log responses:

$client->setLogger(function ($message) {
    \Log::debug('Google Maps API', ['message' => $message]);
});

3. Validate API Keys

Ensure your API key is restricted to your domain in the Google Cloud Console.

4. Check for Mixed Content

If using HTTPS, ensure the Google Maps JS library is loaded over HTTPS:

<script src="https://maps.googleapis.com/maps/api/js"></script>

Extension Points

1. Custom Map Styling

Override the default map styling:

$map->setOptions([
    'styles' => [
        { "featureType": "poi", "stylers": [ { "visibility": "off" } ] }
    ]
]);

2. Add Custom Markers

Extend the Marker class to support custom icons or events:

$marker = $map->addMarker('Custom', $lat, $lng)
    ->setIcon('custom-icon.png')
    ->onClick('alert("Clicked!");');

3. Support for Google Maps SDK for JavaScript

If you need to use the JavaScript SDK alongside this package, initialize it separately:

<script>
    function initMap() {
        // Initialize JS SDK here
    }
</script>

4. Add Proximity Search

Use the places library to search nearby locations:

$places = $client->places()
    ->nearby('restaurant', 40.7128, -74.0060)
    ->radius(1000)
    ->get();

5. Integrate with Laravel Scout

Use geocoding for full-text search with latitude/longitude:

$location = $client->geocode($address);
$model->update([
    'lat' => $location->getLat(),
    'lng' => $location->getLng(),
]);
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