Search code examples
javascriptgoogle-mapspolymergoogle-web-component

Where is the correct place to add an eventListener to a google-map element in Polymer?


I have the following element defined:

<dom-module id="my-element">

  <style>
    :host {
      display: block;
    }
    google-map {
      height: 600px;
    }
  </style>

  <template>
    <geo-location highAccuracy watchpos latitude="{{lat}}" longitude="{{lng}}"></geo-location>
    <google-map id="myMap" latitude="{{lat}}" longitude="{{lng}}" dragEvents="true" zoom="16"></google-map>
    <br>
    <small>Latitude: <b>{{lat}}</b></small><br>
    <small>Longitude: <b>{{lng}}</b></small><br>
  </template>

  <script>
    (function() {
      Polymer({
        is: 'my-element',
        ready: function() {
          this.$.myMap.addEventListener('google-map-dragend', function(e) {
            alert('Map has moved.');
          });
        }
      });
    })();
  </script>

</dom-module>

However, the event listener does not work at all. I've tried calling it in various places but with no success. I'd like to have the event listener call a function every time the user drags the map.

I'm using Polymer 1.0 with Eric Bidelman's excellent geo-locate component. Here is the Documentation for google-map component.


Solution

  • Turns out that the event listener is in the correct place as the ready attribute fires only when all components on a page have finished loading.

    The mistake that I made was actually a convention issue as attributes in the Polymer documentation get translated to code by using '-'es to separate words. I remember reading somewhere in the documentation that attributes should be delimited with dashes in the HTML:

    dragEvents="true" should be drag-events="true"

    Now it works fine.