Polymer Google Maps Element

Including adding/removing markers

by jamstooks

HTML

<script src="//cdnjs.cloudflare.com/ajax/libs/polymer/0.1.4/platform.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?&amp;sensor=false"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/polymer/0.1.4/polymer.js"></script>
<polymer-element name="test-map-component">
    <template>
        <div>
            <button on-click="{{addMarker}}">Add Marker</button>
            <button on-click="{{deleteMarker}}">Delete Marker</button>
            Or right-click to create a marker
          </div>
        <div id="map" style="height: 200px; border: 1px solid #eee;"></div>
    </template>
</polymer-element>
    
 <test-map-component></test-map-component>

JavaScript

Polymer('test-map-component', {
    created: function() {
        console.log("created");
        this.latLng = null;
        this.markers = [];
    },

    ready: function() {
        console.log("ready");
        var mapOptions = {
            center: new google.maps.LatLng(-34.397, 150.644),
            zoom: 6,
            streetViewControl: false,
            panControl: false
        };
        this.map = new google.maps.Map(this.$.map, mapOptions);
        
        // right click to create a waypoint
        var self = this;
        google.maps.event.addListener(this.map, 'rightclick', function(e) {
          self.rightClickListener(e);
        });
    },
    
    addMarker: function() {
        // when the button is clicked
        var newPos = []
        newPos.push(this.map.getCenter().lat() + Math.random());
        newPos.push(this.map.getCenter().lng() + Math.random());
        var latLng = new google.maps.LatLng(newPos[0], newPos[1]);
        this.createMarker(latLng);
    },
    
    rightClickListener: function(event) {
        this.createMarker(event.latLng);
    },
    
    createMarker: function(latLng) {
        // Createa  marker at a latlng
        var m = new google.maps.Marker({
  			map: this.map,
  			position: latLng,
  			draggable: true
  		});
      this.markers.push(m);
    },
    
    deleteMarker: function()  {
        if(this.markers.length > 0) {
          var m = this.markers.pop();
          m.setMap(null);
        }
    }
});