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 Form Type Bundle Laravel Package

bastien-wink/google-map-form-type-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the bundle to composer.json:

    "require": {
        "oh/google-map-form-type-bundle": "dev-master"
    }
    

    Run composer update oh/google-map-form-type-bundle.

  2. Register the Bundle Add to AppKernel.php:

    new Oh\GoogleMapFormTypeBundle\OhGoogleMapFormTypeBundle(),
    
  3. Assetic Configuration Ensure OhGoogleMapFormTypeBundle is included in assetic.bundles in config.yml:

    assetic:
        bundles: ['OhGoogleMapFormTypeBundle']
    
  4. First Use Case Define a form type with the GoogleMapType:

    use Oh\GoogleMapFormTypeBundle\Form\Type\GoogleMapType;
    
    $builder->add('location', GoogleMapType::class);
    

Implementation Patterns

Form Integration

  • Basic Usage Use the GoogleMapType in your form builder:

    $builder->add('latlng', GoogleMapType::class, [
        'label' => 'Select Location',
        'mapped' => true,
        'required' => true,
        'data_class' => null, // Set to your entity if using mapped forms
    ]);
    
  • Customizing Map Options Pass configuration options to tailor the map:

    $builder->add('latlng', GoogleMapType::class, [
        'options' => [
            'center' => [48.8566, 2.3522], // Default center (Paris)
            'zoom' => 12,
            'disableDefaultUI' => true,
        ],
    ]);
    
  • Handling Latitude/Longitude in Entities Ensure your entity has lat and lng properties (or an array latlng):

    class Location
    {
        private $lat;
        private $lng;
    
        public function setLatLng(array $latlng)
        {
            $this->lat = $latlng['lat'];
            $this->lng = $latlng['lng'];
        }
    
        public function getLatLng()
        {
            return [$this->lat, $this->lng];
        }
    }
    
  • Validation Use the bundle’s constraints for validation:

    use Oh\GoogleMapFormTypeBundle\Validator\Constraints as OhAssert;
    
    /**
     * @Assert\Valid()
     * @OhAssert\ValidLatLng()
     */
    private $latlng;
    

Workflows

  1. Edit Existing Locations Pre-populate the map with existing coordinates:

    $form = $this->createForm(LocationType::class, $locationEntity);
    

    The bundle automatically binds lat/lng to the latlng field.

  2. Search and Pin Interaction Users can:

    • Search for an address (updates latlng).
    • Drag the pin to adjust coordinates (updates latlng in real-time).
  3. Submitting Forms The latlng field submits as an array ['lat' => ..., 'lng' => ...], which your entity’s setLatLng() method processes.


Gotchas and Tips

Pitfalls

  1. Outdated Dependencies

    • The bundle is last updated for Symfony 2.1 (2017). Test thoroughly in modern Symfony/Laravel (if using via bridge).
    • Workaround: Use a Symfony 2.x project or wrap the bundle in a custom service for Laravel.
  2. Assetic Requirement

    • The bundle relies on Assetic for JavaScript/CSS. If using Laravel’s asset pipeline (e.g., Laravel Mix), manually include the bundle’s assets:
      // resources/js/app.js
      require('oh-google-map-form-type-bundle');
      
  3. Google Maps API Key

    • The bundle does not handle API keys. Add your key to the map options:
      'options' => [
          'key' => 'YOUR_GOOGLE_MAPS_API_KEY',
      ],
      
    • Alternative: Use a Laravel service to inject the key dynamically.
  4. Entity Mapping Quirks

    • If mapped: true, ensure your entity’s setLatLng() accepts an array (['lat' => ..., 'lng' => ...]).
    • For non-array fields, manually map in the setter:
      public function setLatLng(array $latlng)
      {
          $this->latitude = $latlng['lat'];
          $this->longitude = $latlng['lng'];
      }
      
  5. JavaScript Conflicts

    • The bundle loads Google Maps via a global script. If using Laravel Mix, ensure no duplicate script tags:
      // In your template
      {{ OhGoogleMapFormTypeBundle::includeJavascripts() }}
      

Debugging Tips

  1. Check Console for Errors

    • Open browser dev tools (F12) to verify Google Maps API loads without 403/404 errors.
  2. Validate API Key

  3. Inspect Form Data

    • Use dd($request->request->get('latlng')) to debug submitted data.
  4. Override Templates

    • Customize the map template by extending the bundle’s base template:
      {# templates/OhGoogleMapFormTypeBundle/fields.html.twig #}
      {% extends 'OhGoogleMapFormTypeBundle:Form:fields.html.twig' %}
      {% block google_map_options %}
          {{ parent() }}
          {{ form_widget(form.vat) }} {# Add custom fields #}
      {% endblock %}
      

Extension Points

  1. Custom Map Styling Extend the options array to include map styles:

    'options' => [
        'styles' => [
            { 'featureType': 'poi', 'stylers': [{ 'visibility': 'off' }] }
        ],
    ],
    
  2. Add Markers Programmatically Use JavaScript events to add markers after initialization:

    document.addEventListener('DOMContentLoaded', function() {
        const map = document.getElementById('map-canvas').googleMap;
        map.addMarker({ lat: 40.7128, lng: -74.0060 });
    });
    
  3. Laravel Integration

    • Service Provider: Create a Laravel service to wrap the bundle’s form type:
      namespace App\Services;
      
      use Oh\GoogleMapFormTypeBundle\Form\Type\GoogleMapType;
      
      class GoogleMapService {
          public function createMapField($name, array $options = [])
          {
              return new GoogleMapType($options);
          }
      }
      
    • Blade Directives: Register a Blade directive to simplify usage:
      Blade::directive('googleMap', function ($expression) {
          return "<?php echo \$this->createFormBuilder()->add($expression)->createView(); ?>";
      });
      
      Usage:
      @googleMap('latlng', ['options' => ['center' => [48.8566, 2.3522]]])
      
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.
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle