0

I have the following JQuery plugin:

$(function () {

  $.fn.mapit = function (position, styles) {

    var self = $(this);

    var map = new google.maps.Map(self[0], {
      center: position,
      styles: styles
    });

    var marker = new google.maps.Marker({
      position: position,
      map: map
    });

    return $(this);

  }  
});

And I call it using something like:

google.load("maps", "3", callback: function() {    

  $("div#office").mapit({ lat: 38.73972, lng: -9.144263 }, [{"featureType":"all"}]);

});

The problem is when I call mapit and there is no div#office on the page I get the following error:

TypeError: a is undefined

What should I do in my plugin to avoid this?

Miguel Moura
  • 36,732
  • 85
  • 259
  • 481

1 Answers1

1

As the code is your own plugin, you can extend your plugin to handle multiple selectors/elements by adding

return $(this).each(function() {

to the top of your plugin:

$(function () {
  $.fn.mapit = function (position, styles) {

    return $(this).each(function() {

      var self = this;

      var map = new google.maps.Map(self, {
        center: position,
        styles: styles
      });
      var marker = new google.maps.Marker({
        position: position,
        map: map
      });
    }
  }  
});

For more information, see the plugin tutorial, specifically, using the each method:

https://learn.jquery.com/plugins/basic-plugin-creation/#using-the-each-method

Then, if div#office doesn't exist, there's nothing in the loop and all's good.

freedomn-m
  • 27,664
  • 8
  • 35
  • 57