I love the new Google Maps plugin, it seems really promising.

I am really struggling to manipuluate the map in JS in the new Google Maps plugin.

I have a dynamic map that filters fatal and serious injury crashes (by mode of transportation, outcome, and year) and adds KML layers.

I'm successfully loading the map in Twig — Now I am working through manipulating it in JS but can't seem to get past the first step.

Console: [GM] Unable to find map "mapAlpha"

  {% set fatalities = craft.entries.section('crashes').outcome('fatal').all() %}
  {% set injuries = craft.entries.section('crashes').outcome('injury').all() %}

  {% set options = {
    'id' : 'mapAlpha'
  } %}

  {% set map = googleMaps.map([], options)

  {% do map.markers(fatalities, {
    'icon': '/assets/images/ui/red-dot.png',
    'infoWindowTemplate' : '/modules/info-bubble.twig'
  }) %}
  {% do map.markers(injuries, {
    'icon': '/assets/images/ui/blue-dot.png',
    'infoWindowTemplate' : '/modules/info-bubble.twig'
  }) %}

  {{ map.tag() }}

  {% js %}
    var map = googleMaps.getMap('mapAlpha');
  {% endjs %}

At a glance, it sounds like it's just a matter of waiting for everything to finish loading. You are trying to call a map which has not yet been initialized.

Good news! The tag method includes a callback option which allows you to specify a JavaScript function to be called after the map has finished loading...

{{ map.tag({
    'callback': 'moreJavascript'
}) }}

{% js %}
    function moreJavascript() {
        var map = googleMaps.getMap('mapAlpha');
{% endjs %}

Take a look at this practical example of how someone could use the callback option to enable marker clustering... I know that you aren't trying to cluster your markers, but the broader execution is the same.

  • Pefect — I've successfully added a KML layer, is there an example of toggling a map layer on/off? – Charlie Triplett Apr 11 at 21:54
  • That's a separate question, but the answer might be no. I've added a feature request on GitHub, so feel free to follow along there for developing information. – Lindsey D Apr 12 at 22:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.