1

In the previous version of the Google Maps plugin (Smart Maps) I used something similar to this to toggle multiple KML layers:

    var streetLayer = new google.maps.KmlLayer('https://www.comovisionzero.org/assets/data/high-crash-network.kml', {
        preserveViewport: true,
        suppressInfoWindows: false
    })
    function toggleStreetLayer() {
        if( $("#streets").is(':checked') ) {
            streetLayer.setMap(map);
        }
        else {
            streetLayer.setMap(null);
        }
    }

In the new version, I'm trying to use the callback and map.kml functionality, but I'm having difficulty toggling the KML layer off:

  {{ map.tag({
    'callback': 'mapFilters'
    })
  }}
  <script>
  {% js %}
    function mapFilters() {
      var map = googleMaps.getMap('mapAlpha');


      function showLayer(kmlUrl) {
        map.kml(kmlUrl, {
          'preserveViewport': true
        });
      };

      function toggleStreetLayer() {
        if( $("#streets").is(':checked') ) {
          showLayer('https://www.comovisionzero.org/assets/data/high-crash-network.kml');
        }
        else {
          showLayer(null);
        }
      }

      $("input").change(function() {
          toggleStreetLayer();
      });

    }
  {% endjs %}
  </script>

Am I even close to being on the right track?

2
  • Easier-to-use KML functions are coming soon, if you don't mind waiting a few weeks. – Lindsey D May 19 at 18:18
  • Just added a comprehensive answer, thanks for your patience! :) – Lindsey D Jun 8 at 22:32
3

As of v4.0.10 of the Google Maps plugin, three new functions have been added for working with KML layers...

These methods are explained in greater detail in the KML Layers documentation.


In other words, your example might look something more like this...

{# Create the map #}
{% set map = googleMaps.map(locations, {
    'id': 'mapAlpha',
}) %}

{# Set the KML layer URL #}
{% set url = 'https://www.comovisionzero.org/assets/data/high-crash-network.kml' %}

{# Add the KML layer #}
{% do map.kml(url, {
    'id': 'my-kml',
    'kmlLayerOptions': {
        'preserveViewport': true
    }
}) %}

{# Display the map #}
{{ map.tag() }}

{% js %}
// Toggle the street layer KML
function toggleStreetLayer() {

    // Get the existing map
    var map = googleMaps.getMap('mapAlpha');

    // Show or hide the KML layer
    if( $("#streets").is(':checked') ) {
        map.showKml('my-kml');
    }
    else {
        map.hideKml('my-kml');
    }

}
{% endjs %}

Worth keeping in mind that there are several other ways to approach this as well, since there are now strong parallels between JS, Twig, and PHP.

Hope that helps!

1

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.