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

Ux Leaflet Map Laravel Package

symfony/ux-leaflet-map

Symfony UX package integrating Leaflet maps into your app with Stimulus controllers and Twig components. Easily render interactive maps, markers, and layers while keeping configuration in PHP/Twig and assets managed via Symfony’s UX tooling.

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Setup
1. **Installation**
   ```bash
   composer require symfony/ux-leaflet-map ^2.35
   npm install leaflet @symfony/ux-leaflet-map

Add to webpack.config.js (ensure compatibility with Symfony UX 3.x):

Encore
    .addEntry('app', './assets/app.js')
    .enableStimulusBridge('./assets/controllers.json')
    .copyFiles(['public/images/**/*'])
    .configureBabel((config) => {
        config.plugins.push('@babel/plugin-proposal-class-properties');
    });
  1. Basic Controller Integration (Symfony UX 3.x compatible)

    use Symfony\UX\LeafletMap\MapController;
    
    class LocationController extends AbstractController
    {
        #[Route('/map', name: 'map')]
        public function map(MapController $mapController): Response
        {
            return $this->render('location/map.html.twig', [
                'mapController' => $mapController,
            ]);
        }
    }
    
  2. First Template Usage (Symfony UX 3.x)

    {{ include_controller(mapController) }}
    
  3. Basic JavaScript Activation (Symfony UX 3.x)

    // assets/controllers/map_controller.js
    import { Controller } from '@hotwired/stimulus';
    import { MapController } from '@symfony/ux-leaflet-map';
    
    export default class extends Controller {
        static values = { ...MapController.values };
        connect() { MapController.connect(this); }
    }
    

Implementation Patterns

Common Workflows

1. Static Map Initialization (Symfony UX 3.x)

{{ include_controller(mapController, {
    'center': [48.8566, 2.3522],  // Paris coordinates
    'zoom': 12,
    'markers': [
        { 'lat': 48.8584, 'lng': 2.2945, 'popup': 'Eiffel Tower' }
    ]
}) }}

2. Dynamic Data Binding with Symfony UX 3.x

// Controller
$mapController->setOptions([
    'center' => [$lat, $lng],
    'markers' => $this->getMarkersFromDatabase(),
    'theme' => 'dark', // New in v2.35 (optional)
]);

3. Stimulus Controller Customization (Symfony UX 3.x)

// assets/controllers/map_controller.js
import { Controller } from '@hotwired/stimulus';
import { MapController } from '@symfony/ux-leaflet-map';

export default class extends Controller {
    static values = {
        ...MapController.values,
        customOption: { type: String, default: 'default' } // Symfony UX 3.x default support
    };

    connect() {
        MapController.connect(this);
        this.map.setView(this.centerValue, this.zoomValue);
        this.map.setMaxBounds([[40, -10], [60, 10]]);
    }
}

4. Integration with Forms (Symfony UX 3.x)

{# location/_form.html.twig #}
<div {{ stimulus_controller('map', {
    'center': [{{ form.lat.data }}, {{ form.lng.data }}],
    'zoom': 14,
    'theme': 'light' // New theme option
}) }}>
    {{ include_controller(mapController) }}
</div>

{{ form_row(form.lat) }}
{{ form_row(form.lng) }}

5. Event Handling (Symfony UX 3.x)

// assets/controllers/map_controller.js
export default class extends Controller {
    move(event) {
        this.dispatch('map-moved', { detail: { lat: event.latLng.lat, lng: event.latLng.lng } });
    }

    // New in v2.35: TypeScript support
    declare @customOption: string;
}
{# In parent template #}
<div data-controller="map" data-map-action="move->parent#handleMapMove">
    {{ include_controller(mapController) }}
</div>

Advanced Patterns

Layer Management (Symfony UX 3.x)

// assets/controllers/map_controller.js
export default class extends Controller {
    addLayer() {
        L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
            attribution: '© OpenStreetMap contributors'
        }).addTo(this.map);
    }
}

Geocoding Integration (Symfony UX 3.x)

// Controller
use Symfony\UX\LeafletMap\Geocoder\GeocoderInterface;

class LocationController extends AbstractController
{
    public function __construct(private GeocoderInterface $geocoder) {}

    #[Route('/search')]
    public function search(string $query): Response
    {
        $results = $this->geocoder->geocode($query);
        return $this->render('location/search.html.twig', [
            'results' => $results,
        ]);
    }
}

Cluster Markers (Symfony UX 3.x)

{{ include_controller(mapController, {
    'markers': markers|map((marker) => {
        'lat': marker.latitude,
        'lng': marker.longitude,
        'popup': marker.name,
        'icon': {
            'iconUrl': '/icons/' ~ marker.type ~ '.png',
            'iconSize': [32, 32]
        }
    }),
    'clusterOptions': {
        'spiderfyOnMaxZoom': true,
        'showCoverageOnHover': false
    },
    'theme': 'dark' // New theme option
}) }}

Gotchas and Tips

Common Pitfalls

  1. Symfony UX 3.x Compatibility

    • Symptom: Stimulus controllers not working after upgrade.
    • Fix: Ensure webpack.config.js includes Babel plugin for class properties and update Stimulus imports:
      import { Controller } from '@hotwired/stimulus';
      
  2. Coordinate Order

    • Gotcha: Leaflet uses [lat, lng] but some APIs return [lng, lat].
    • Fix: Normalize coordinates in your controller:
      $coordinates = [$marker['lat'], $marker['lng']];
      
  3. Tile Layer CORS Issues

    • Symptom: Blank map or CORS errors.
    • Fix: Use CORS-enabled tile providers (e.g., OpenStreetMap, Mapbox with access token).
  4. Stimulus Controller Naming

    • Gotcha: Using MapController as a class name conflicts with Symfony’s MapController.
    • Fix: Rename your Stimulus controller (e.g., LeafletMapController).
  5. Z-Index Conflicts

    • Symptom: Markers/popups hidden behind other elements.
    • Fix: Explicitly set zIndex in CSS:
      .leaflet-container { z-index: 1000; }
      

Debugging Tips

  1. Check Webpack Output

    • Run npm run dev and inspect the browser console for Stimulus-related errors. Ensure Symfony UX 3.x compatibility:
      npm install @hotwired/stimulus@^3.0
      
  2. Inspect Stimulus Controllers

    • Use the Stimulus DevTools (Chrome extension) to verify controller connections.
  3. Log Map Events

    connect() {
        this.map.on('move', (e) => {
            console.log('Map moved:', e.target.getCenter());
        });
    }
    
  4. Validate JSON Options

    • Ensure all options passed to include_controller are valid JSON. Use json_encode() in Twig:
      {{ include_controller(mapController, {
          'options': mapOptions|json_encode|raw,
          'theme': 'light' // New theme option
      }) }}
      

Configuration Quirks

  1. Default Center

    • If no center is provided, Leaflet defaults to [0, 0] (Atlantic Ocean). Always specify a center.
  2. Marker Icons

    • Custom icons require full paths (e.g., /images/marker.png). Use asset() in Twig:
      'icon': {
          'iconUrl': '{{ asset('images/marker.png') }}',
          'iconSize': [25, 41]
      }
      
  3. Responsive Design

    • Leaflet maps are not inherently responsive. Add CSS:
      .leaflet-container {
          width: 100%;
          height: 100vh;
      }
      
  4. New Theme Options (v2.35)

    • Options: 'light', 'dark', or 'osm' (OpenStreetMap default).
    • Usage:
      {{ include_controller(mapController, { 'theme': 'dark' }) }}
      

Extension

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.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui