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

egeloen/google-map

PHP 5.6+ Google Maps JavaScript API v3 integration. Build and render maps with configurable controls, overlays, events and services via helpers, plus easy API script rendering with your key.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require egeloen/google-map
    

    Add the package to config/app.php under providers if using Laravel’s service container.

  2. First Use Case: Render a basic map with a marker in a Laravel Blade view:

    use Ivory\GoogleMap\Helper\Builder\MapHelperBuilder;
    use Ivory\GoogleMap\Map;
    use Ivory\GoogleMap\Overlay\Marker;
    
    $map = new Map();
    $marker = new Marker(new \Ivory\GoogleMap\Base\Coordinate(48.8584, 2.2945));
    $map->getOverlayManager()->addMarker($marker);
    
    $mapHelper = MapHelperBuilder::create()->build();
    echo $mapHelper->render($map);
    
  3. Key Files:

    • resources/views/maps/basic.blade.php: Placeholder for map rendering.
    • config/services.php: Add Google Maps API key (if using helpers).

Implementation Patterns

Core Workflows

  1. Map Initialization:

    $map = new Map();
    $map->setCenter(new \Ivory\GoogleMap\Base\Coordinate(48.8584, 2.2945))
        ->setZoom(12);
    
  2. Overlay Management:

    • Markers:
      $marker = new Marker($coordinate, ['title' => 'Paris']);
      $map->getOverlayManager()->addMarker($marker);
      
    • Info Windows:
      $infoWindow = new InfoWindow('Paris, France');
      $marker->setInfoWindow($infoWindow);
      
  3. Event Handling:

    $map->addEventListener('click', function($event) {
        // Handle click event
    });
    
  4. Layer Integration:

    $geoJsonLayer = new GeoJsonLayer('path/to/file.geojson');
    $map->getLayerManager()->addGeoJsonLayer($geoJsonLayer);
    
  5. Service Integration (e.g., Geocoding):

    $geocoder = new \Ivory\GoogleMap\Service\Geocoder();
    $geocoder->setAddress('Eiffel Tower, Paris');
    $geocoder->setCallback(function($result) {
        $map->setCenter($result->getLocation());
    });
    

Laravel-Specific Patterns

  1. Service Container Binding:

    $this->app->bind('google-map', function() {
        return new Map();
    });
    
  2. Blade Directives: Create a custom directive for reusable map rendering:

    Blade::directive('map', function($expression) {
        return "<?php echo app('google-map')->render($expression); ?>";
    });
    

    Usage:

    @map($map)
    
  3. Configuration: Store API key and defaults in config/google-map.php:

    return [
        'api_key' => env('GOOGLE_MAPS_API_KEY'),
        'defaults' => [
            'zoom' => 10,
            'center' => [48.8584, 2.2945],
        ],
    ];
    

Gotchas and Tips

Pitfalls

  1. API Key Management:

    • Ensure the API key is restricted to your domain in the Google Cloud Console.
    • Never hardcode keys in Blade templates or client-side JavaScript.
  2. Coordinate Precision:

    • Use floatval() for coordinates to avoid precision issues:
      $coordinate = new \Ivory\GoogleMap\Base\Coordinate(floatval($lat), floatval($lng));
      
  3. Event Listener Scope:

    • Events like click or zoom_changed require the map to be fully rendered. Attach listeners after rendering:
      $mapHelper->render($map);
      $map->addEventListener('click', $callback);
      
  4. Marker Clustering:

    • Enable clustering before adding markers:
      $map->getOverlayManager()->getMarkerCluster()->setType(MarkerClusterType::MARKER_CLUSTERER);
      foreach ($markers as $marker) {
          $map->getOverlayManager()->addMarker($marker);
      }
      
  5. Static Maps:

    • Static maps have a size limit (640x640 pixels). For larger maps, use dynamic rendering.

Debugging Tips

  1. Console Logs: Use JavaScript console.log in custom callbacks to debug events:

    $map->addEventListener('click', function($event) {
        $event->setCallback("console.log('Clicked at: ' + event.latLng.toUrlValue());");
    });
    
  2. Variable Naming Conflicts:

    • Ensure custom variable names (e.g., setVariable('custom_map')) don’t conflict with existing JavaScript variables.
  3. CORS Issues:

    • If using custom services (e.g., Geocoder), ensure your server handles CORS for API requests.

Extension Points

  1. Custom Overlays: Extend the OverlayInterface to create new overlay types:

    class CustomOverlay implements OverlayInterface {
        public function render(Map $map) { /* ... */ }
    }
    
  2. Helper Extensions: Override MapHelper to add Laravel-specific features:

    class LaravelMapHelper extends MapHelper {
        public function renderWithAuth(Map $map) {
            $this->setApiKey(config('google-map.api_key'));
            return parent::render($map);
        }
    }
    
  3. Service Decorators: Decorate services (e.g., Geocoder) to add middleware:

    class CachedGeocoder implements GeocoderInterface {
        private $geocoder;
    
        public function __construct(Geocoder $geocoder) {
            $this->geocoder = $geocoder;
        }
    
        public function setAddress($address) {
            // Add caching logic
            $this->geocoder->setAddress($address);
        }
    }
    
  4. Dynamic Styling: Use the MapType class to apply custom map styles:

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

Performance Tips

  1. Lazy Loading: Load maps dynamically via AJAX to reduce initial page load time:

    // In Blade
    <div id="map-container"></div>
    <script>
        fetch('/load-map')
            .then(response => response.text())
            .then(html => {
                document.getElementById('map-container').innerHTML = html;
            });
    </script>
    
  2. Cluster Optimization: For large datasets, use MarkerClusterer with gridSize:

    $map->getOverlayManager()->getMarkerCluster()
        ->setOption('gridSize', 50);
    
  3. Image Optimization:

    • Compress ground overlay images to reduce load times.
    • Use base64-encoded images for small overlays to avoid extra HTTP requests.
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.
besmartand-pro/php-quality-config
sentix/ai-chatbot
terminal42/code-quality-tools
codifyo/ts-generator-bundle
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