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 Location Laravel Package

anotterweb/ux-location

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Setup
1. **Install the package**:
   ```bash
   composer require anotterweb/ux-location
  1. Enable the bundle in config/bundles.php:
    Anotterweb\UxLocation\AnotterWebUxLocationBundle::class => ['all' => true],
    
  2. Configure Mapbox token in config/packages/anotterweb_ux_location.yaml:
    anotterweb_ux_location:
        mapbox_access_token: '%env(MAPBOX_ACCESS_TOKEN)%'
    
  3. Install Mapbox dependencies (if using AssetMapper):
    php bin/console importmap:require mapbox-gl mapbox-gl/dist/mapbox-gl.css
    

First Use Case

Add the LocationType to a form:

use Anotterweb\UxLocation\Form\Type\LocationType;

$builder->add('location', LocationType::class, [
    'label' => 'Store Location',
]);

Render in Twig:

{{ form_row(form.location) }}

Implementation Patterns

Common Workflows

  1. Form Integration:

    • Use LocationType as a replacement for TextType where geographic coordinates are needed.
    • Example: Store registration, event location, or delivery address forms.
  2. Customization:

    • Override default map settings per field:
      $builder->add('location', LocationType::class, [
          'default_lat' => 40.7128, // New York
          'default_lng' => -74.0060,
          'map_height' => '400px',
      ]);
      
  3. Data Handling:

    • The field stores coordinates as a string in lat,lng format (e.g., 48.8566,2.3522).
    • Validate input in your controller:
      $data = $form->getData();
      $coordinates = explode(',', $data['location']);
      if (count($coordinates) !== 2) {
          // Handle invalid format
      }
      
  4. Symfony UX Integration:

    • Leverage Stimulus controllers for dynamic updates (e.g., real-time validation).
    • Example: Use data-controller="location" in Twig to attach custom logic.

Advanced Patterns

  1. Dynamic Map Styling:

    • Use map_style option to switch between Mapbox styles (e.g., mapbox://styles/mapbox/streets-v11).
    • Override globally in config or per field.
  2. Custom Markers:

    • Extend the bundle’s Stimulus controller to add custom icons:
      // assets/controllers/location_controller.js
      import { Controller } from '@hotwired/stimulus';
      export default class extends Controller {
          connect() {
              this.map.addSource('custom-marker', {
                  type: 'geojson',
                  data: { type: 'FeatureCollection', features: [...] }
              });
          }
      }
      
  3. Geocoding:

    • Combine with the Mapbox Geocoding API to convert addresses to coordinates.
    • Example: Use a separate TextType for address input, then trigger the map via JavaScript.
  4. Validation:

    • Add constraints to ensure valid coordinates:
      use Symfony\Component\Validator\Constraints as Assert;
      
      $builder->add('location', LocationType::class, [
          'constraints' => [
              new Assert\Regex('/^[-+]?([1-8]?\d(\.\d+)?|90(\.0+)?),\s*[-+]?(180(\.0+)?|((1[0-7]\d)|([1-9]?\d))(\.\d+)?)$/'),
          ],
      ]);
      

Gotchas and Tips

Pitfalls

  1. Missing Mapbox Token:

    • If MAPBOX_ACCESS_TOKEN is not set, the map will fail to load. Always validate the env variable:
      # config/packages/dev/anotterweb_ux_location.yaml
      anotterweb_ux_location:
          mapbox_access_token: '%env(MAPBOX_ACCESS_TOKEN)%'
      
    • Debug: Check browser console for 401 Unauthorized errors.
  2. AssetMapper Issues:

    • Ensure mapbox-gl and its CSS are imported. Run:
      php bin/console debug:asset-mapper
      
    • If using Symfony 7+, verify importmap:require is used instead of encore.
  3. Coordinate Format:

    • The field expects lat,lng format. Reject malformed input early:
      if (!preg_match('/^[-+]?\d+(\.\d+)?,\s*[-+]?\d+(\.\d+)?$/', $data['location'])) {
          $form->addError(new FormError('Invalid coordinates format.'));
      }
      
  4. Form Theme Conflicts:

    • If the map doesn’t render, clear cache and check for template overrides:
      php bin/console cache:clear
      
    • Verify templates/form/fields.html.twig isn’t overriding the bundle’s templates.
  5. Symfony 8+ Compatibility:

    • Ensure symfony/asset-mapper and symfony/ux are installed:
      composer require symfony/asset-mapper symfony/ux
      

Debugging Tips

  1. Browser DevTools:

    • Inspect the map container for errors (e.g., missing data-controller or data-action attributes).
    • Check the Network tab for failed requests to Mapbox APIs.
  2. Log Configuration:

    • Enable debug mode to log bundle configuration:
      # config/packages/dev/monolog.yaml
      handlers:
          main:
              type: stream
              path: "%kernel.logs_dir%/%kernel.environment%.log"
              level: debug
      
  3. Stimulus Debugging:

    • Add data-controller="location" to the map container in Twig:
      {{ form_widget(form.location, { 'attr': {'data-controller': 'location'} }) }}
      
    • Use console.log in custom Stimulus controllers to trace execution.

Extension Points

  1. Custom Stimulus Controllers:

    • Override the default controller by creating a new one in assets/controllers/location_controller.js:
      import { LocationController } from '@anotterweb/ux-location';
      export default class extends LocationController {
          connect() {
              super.connect();
              // Add custom logic (e.g., disable map interaction)
              this.map.boxZoom.disable();
          }
      }
      
    • Register it in Twig:
      {{ form_widget(form.location, { 'attr': {'data-controller': 'location--custom'} }) }}
      
  2. Form Events:

    • Listen to form events to update the map dynamically:
      $form->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) {
          $data = $event->getData();
          if ($data['location']) {
              $event->getForm()->add('location', LocationType::class, [
                  'default_lat' => explode(',', $data['location'])[0],
                  'default_lng' => explode(',', $data['location'])[1],
              ]);
          }
      });
      
  3. Twig Extensions:

    • Create a custom Twig extension to generate map URLs with query parameters:
      // src/Twig/MapExtension.php
      class MapExtension extends \Twig\Extension\AbstractExtension {
          public function getFunctions() {
              return [
                  new \Twig\TwigFunction('map_url', [$this, 'getMapUrl']),
              ];
          }
          public function getMapUrl(array $coordinates) {
              return "https://api.mapbox.com/styles/v1/mapbox/streets-v11/static/pin-s+ff0000($coordinates[1],$coordinates[0])/$coordinates[1],$coordinates[0],14/600x400?access_token=%env(MAPBOX_ACCESS_TOKEN)%";
          }
      }
      
    • Use in Twig:
      <img src="{{ map_url([48.8566, 2.3522]) }}" alt="Preview">
      
  4. Database Storage:

    • Store coordinates in a Point type column (PostgreSQL) or as separate latitude/longitude fields:
      // Doctrine Entity
      /**
       * @ORM\Column(type="string", length=50)
       */
      private $location; // "lat,lng"
      
      // OR
      /**
       * @ORM\Column(type="decimal", precision=10, scale=8)
       */
      private $latitude;
      /**
       * @ORM\Column(type="decimal", precision=11, scale=8)
       */
      
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