Search code examples
google-mapspolymer

how do you programatically add markers to the polymer google map element


Trying out polymer and wanted to know how to add a marker element to the polymer element. I know how to add the marker to a standard google map. Should I just insert a marker object into the google-map elements marker array? If so whats the signature and is there an example? Do I need to call some sort of map init or refresh after I do so, or does it update automatically?

   (function() {
      Polymer({
        is: 'users-map',

        created: function(){
          this.loadMap(this.data[0]);
        },

        loadMap: function(row) {
          var map = document.querySelector('#users-location-map');
          row.users.forEach(function (user) {
            var location = user.location;
            var markerOptions = {
              position: {lat: location[1], lng: location[0]},
              //map: map //can't set this otherwise it throws an error on finding the google library
            };
            if (!user.online) {
              markerOptions.icon = 'http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|666666';
            }

            map.markers.push(something); //how should I instanstiate this something
//            new google.maps.Marker(markerOptions); //normally I would just do this 
          });
        },

The answer below works if I comment out the map assingment.


Solution

  • It depends if you are using the google-map and google-map-marker or the google map API directly.

    If you use the google-map and google-map-marker elements this approach should work:

    marker = document.createElement('google-map-marker');
    marker.longitude = location[0];
    marker.latitude = location[1];
    marker.icon = 'ICON_UR'
    Polymer.dom(this.$.map).appendChild(marker);
    

    If you use the google map API directly your normal appraoch with new google.maps.Marker(markerOptions); should work fine.