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

Simple G Maps Laravel Package

alfamegaxq/simple-g-maps

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require alfamegaxq/simple-g-maps
    

    Register the bundle in config/bundles.php (Symfony 4+) or AppKernel.php (Symfony 3):

    SimpleGMapsBundle\SimpleGMapsBundle::class => ['all' => true],
    
  2. Route Configuration: Add to config/routes.yaml:

    google_autosuggest:
        resource: "@SimpleGMapsBundle/Controller/"
        type: annotation
    
  3. Include Dependencies: Ensure your layout includes:

    <!-- In <head> -->
    <link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
    
    <!-- Before </body> -->
    <script src="{{ asset('bundles/gmaps/js/script.js') }}"></script>
    
  4. First Use Case: Render a city autocomplete input in a Twig template:

    {{ render(controller('SimpleGMapsBundle:Suggest:renderCitySuggest', {
        inputParams: 'name="city" class="city-autocomplete" placeholder="Enter city"',
        language: 'en',
        country: 'us'
    })) }}
    

Implementation Patterns

Common Workflows

  1. Dynamic Country/Language Handling: Pass dynamic values via Twig:

    {% set country = user.countryCode %}
    {{ render(controller('SimpleGMapsBundle:Suggest:renderCitySuggest', {
        inputParams: '...',
        country: country,
        language: country == 'de' ? 'de' : 'en'
    })) }}
    
  2. Integration with Forms: Use with Symfony Forms:

    $builder->add('city', TextType::class, [
        'attr' => [
            'class' => 'city-autocomplete',
            'data-country' => $user->getCountryCode()
        ]
    ]);
    

    Render the form with the bundle’s JS included.

  3. API-Driven Extensions: Extend the backend logic by subclassing SimpleGMapsBundle\Controller\SuggestController and overriding renderCitySuggestAction to:

    • Add custom validation.
    • Fetch additional data (e.g., weather) via Guzzle.
    • Log API calls for analytics.
  4. Asset Management: Override the default JS/CSS by:

    • Publishing assets:
      php bin/console assets:install public
      
    • Customizing script.js via resources/assets/gmaps/js/script.js (Symfony 4+ asset pipeline).

Gotchas and Tips

Pitfalls

  1. Deprecated Symfony 3.1:

    • The bundle targets Symfony 3.1. Use a wrapper like symfony/webpack-encore-bundle for asset management if upgrading to Symfony 4/5.
    • Fix: Polyfill AppKernel or use config/bundles.php with a compatibility layer.
  2. Missing Google Maps Logo:

    • The README mandates including "Powered by Google" for non-Maps use. Add this near the input:
      <div class="gmaps-attribution">
          <a href="https://www.google.com/maps">Powered by Google</a>
      </div>
      
  3. jQuery UI Dependency:

    • The bundle requires jQuery UI’s autocomplete widget. Conflicts may arise if other plugins use $ or jQuery.
    • Fix: Wrap initialization in:
      (function($) {
          // Bundle's JS code here
      })(jQuery);
      
  4. API Rate Limits:

    • Google’s Places API has quotas. Cache responses aggressively:
      // In a custom controller extension
      $cache = $this->get('doctrine_cache.providers.gmaps');
      $cachedData = $cache->fetch('gmaps_cities_' . $country);
      

Debugging Tips

  1. Check Network Requests:

    • Open DevTools (F12) → Network tab. Verify the /suggest/city endpoint returns valid JSON.
    • Common Issue: Missing Accept: application/json header. Add to Guzzle client:
      $client->getConfig()->set('headers', ['Accept' => 'application/json']);
      
  2. Log API Errors:

    • Extend the controller to log Guzzle exceptions:
      try {
          $response = $client->request('GET', $url);
      } catch (\GuzzleHttp\Exception\RequestException $e) {
          $this->get('logger')->error('GMaps API Error', ['response' => $e->getResponse()->getBody()]);
          throw new \RuntimeException('Failed to fetch data from Google Maps API');
      }
      
  3. Validate Input Params:

    • The inputParams Twig variable must be a string. Escape dynamic values:
      {% set params = 'name="city" class="city-autocomplete" data-attr="' ~ attribute|e('html_attr') ~ '"' %}
      

Extension Points

  1. Custom Autocomplete Sources:

    • Override SimpleGMapsBundle/Resources/views/Suggest/renderCitySuggest.html.twig to use a different template engine or add markers.
  2. Add New Endpoints:

    • Clone SuggestController and add methods for:
      • Geocoding (/geocode).
      • Distance Matrix (/distance).
    • Example:
      /**
       * @Route("/distance", name="gmaps_distance")
       */
      public function distanceMatrixAction(Request $request) {
          $origin = $request->query->get('origin');
          $destination = $request->query->get('destination');
          // Use Guzzle to call Google's Distance Matrix API
      }
      
  3. Configuration via Parameters:

    • Define default values in config/packages/simple_g_maps.yaml:
      simple_g_maps:
          default_country: 'us'
          api_key: '%env(GOOGLE_MAPS_API_KEY)%'
          cache_ttl: 3600  # 1 hour
      
    • Access in controllers via $this->getParameter('simple_g_maps.default_country').
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.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware