gmap3.js 30.4 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131
/*!
 *  GMAP3 Plugin for jQuery
 *  Version  : 7.1
 *  Date     : 2016/04/17
 *  Author   : DEMONTE Jean-Baptiste
 *  Contact  : jbdemonte@gmail.com
 *  Web site : http://gmap3.net
 *  Licence  : GPL-3.0+
 */
(function ($, window, document) {
  "use strict";

  var gm, services = {}, loadOptions,

  // Proxify functions to get shorter minimized code
    when = $.when,
    extend = $.extend,
    isArray = $.isArray,
    isFunction = $.isFunction,
    deferred = $.Deferred;

  /**
   * Duplicate option to never modify original object
   * @param {Object} options
   * @returns {Object}
   */
  function dupOpts(options) {
    return extend(true, {}, options || {});
  }

  /**
   * Slice an array like
   * @params {Array|Object}
   * @params {Number} [start]
   * @params {Number} [end]
   * @returns {Array}
   */
  function slice() {
    var fn = Array.prototype.slice,
      args = fn.call(arguments, 1);
    return fn.apply(arguments[0], args);
  }

  /**
   * Return true if value is undefined
   * @param {*} value
   * @returns {Boolean}
   */
  function isUndefined(value) {
    return typeof value === 'undefined';
  }

  /**
   * Equivalent to Promise.all
   * @param {Deferred[]} deferreds
   * @returns {Deferred}
   */
  function all(deferreds) {
    return when.apply($, deferreds);
  }

  /**
   * Equivalent to Promise.resolve
   * @param {*} value
   * @returns {Deferred}
   */
  function resolved(value) {
    return when().then(function () {
      return value;
    });
  }

  /**
   * return the distance between 2 latLng in meters
   * @param {LatLng} origin
   * @param {LatLng} destination
   * @returns {Number}
   **/
  function distanceInMeter(origin, destination) {
    var m = Math,
      pi = m.PI,
      e = pi * origin.lat() / 180,
      f = pi * origin.lng() / 180,
      g = pi * destination.lat() / 180,
      h = pi * destination.lng() / 180,
      cos = m.cos,
      sin = m.sin;
    return 1000 * 6371 * m.acos(m.min(cos(e) * cos(g) * cos(f) * cos(h) + cos(e) * sin(f) * cos(g) * sin(h) + sin(e) * sin(g), 1));
  }

  function ready(fn) {
    if (document.readyState != 'loading'){
      fn();
    } else {
      document.addEventListener('DOMContentLoaded', fn);
    }
  }

  function serialize(obj) {
    return objectKeys(obj).map(function (key) {
      return encodeURIComponent(key) + "=" + encodeURIComponent(obj[key]);
    }).join("&");
  }

  // Auto-load google maps library if needed
  (function () {
    var dfd = deferred(),
      cbName = '__gmap3',
      script;

    $.holdReady(true);

    ready(function () {
      if (window.google && window.google.maps || loadOptions === false) {
        dfd.resolve();
      } else {
        // callback function - resolving promise after maps successfully loaded
        window[cbName] = function () {
          delete window[cbName];
          dfd.resolve();
        };
        script = document.createElement('script');
        script.type = 'text/javascript';
        script.src = 'https://maps.googleapis.com/maps/api/js?callback=' + cbName + (loadOptions ? '&' + (typeof loadOptions === 'string' ? loadOptions : serialize(loadOptions)) : '');
        $("head").append(script);
      }
    });

    return dfd.promise();
  })().then(function () {
    $.holdReady(false);
  });

  /**
   * Instantiate only once a google service
   * @param {String} name
   * @returns {Object}
   */
  function service(name) {
    if (!services[name]) {
      services[name] = gmElement(name);
    }
    return services[name];
  }

  /**
   * Return GoogleMap Class (or overwritten by user) instance
   * @param {String} name
   * @returns {Object}
   */
  function gmElement(name) {
    var cls = gm[name];

    function F(args) {
      return cls.apply(this, args);
    }
    F.prototype = cls.prototype;

    return new F(slice(arguments, 1));
  }

  /**
   * Resolve a GeocodeRequest
   * https://developers.google.com/maps/documentation/javascript/geocoding
   * @param {String|Object} request
   * @returns {Deferred}
   */
  function geocode(request) {
    var dfd = deferred();
    if (typeof request === 'string') {
      request = {
        address: request
      };
    }
    service('Geocoder').geocode(request, function(results, status) {
      if (status === gm.GeocoderStatus.OK) {
        dfd.resolve(results[0].geometry.location);
      } else {
        dfd.reject();
      }
    });
    return dfd;
  }

  /**
   * Callable function taking a parameter as string
   * @callback StringCallback
   * @param {String}
   */

  /**
   * Split a string and execute a function on each item
   * @param {String} str - Space separated list of items
   * @param {StringCallback} fn - Callback function
   */
  function foreachStr(str, fn) {
    str.split(' ').forEach(fn);
  }

  /**
   * Execute a function on each items if items is an array and on items as a single element if it is not an array
   * @param {Array|*} items - Items to execute foreach callback on
   * @param {Function} fn - Callback function
   */
  function foreach(items, fn) {
    (isArray(items) ? items : [items]).forEach(fn);
  }

  /**
   * Return Object keys
   * @param {Object} obj
   * @returns {String[]}
   */
  function objectKeys(obj) {
    return Object.keys(obj);
  }

  /**
   * Return Object values
   * @param {Object} obj
   * @returns {*[]}
   */
  function objectValues(obj) {
    return objectKeys(obj).map(function (key) {
      return obj[key];
    });
  }

  /**
   * Resolution function
   * @callback OptionCallback
   * @param {Object} options
   * @returns {Deferred|*}
   */

  /**
   * Convert bounds from array [ n, e, s, w ] to google.maps.LatLngBounds
   * @param {Object} options - Container of options.bounds
   * @param {OptionCallback} fn
   * @returns {Deferred}
   */
  function resolveLatLngBounds(options, fn) {
    options = dupOpts(options);
    if (options.bounds) {
      options.bounds = toLatLngBound(options.bounds);
    }
    return resolved(fn(options));
  }

  /**
   * Resolve an address location / convert a LatLng array to google.maps.LatLng object
   * @param {Object} options
   * @param {String} key - LatLng key name in options object
   * @param {OptionCallback} fn
   * @returns {Deferred}
   */
  function resolveLatLng(options, key, fn) {
    var dfd = deferred();
    options = dupOpts(options);
    when()
      .then(function () {
        var address = options.address;
        if (address) {
          delete options.address;
          return geocode(address).then(function (latLng) {
            options[key] = latLng;
          });
        }
        options[key] = toLatLng(options[key]);
      })
      .then(function () {
        dfd.resolve(fn(options));
      });
    return dfd;
  }

  /**
   * Convert an array of mixed LatLng to google.maps.LatLng object
   * No address resolution here
   * @param {Object} options
   * @param {String} key - Array key name in options object
   * @param {OptionCallback} fn
   * @returns {Deferred}
   */
  function resolveArrayOfLatLng(options, key, fn) {
    options = dupOpts(options);
    options[key] = (options[key] || []).map(function (item) {
      return toLatLng(item);
    });
    return resolved(fn(options));
  }

  /**
   * Convert a LatLng array to google.maps.LatLng
   * @param {Array|*} mixed
   * @param {Boolean} [convertLiteral]
   * @returns {LatLng}
   */
  function toLatLng(mixed, convertLiteral) {
    return isArray(mixed) ? new gm.LatLng(mixed[0], mixed[1]) : (convertLiteral && mixed && !(mixed instanceof gm.LatLng) ? new gm.LatLng(mixed.lat, mixed.lng) : mixed);
  }

  /**
   * Convert a LatLngBound array to google.maps.LatLngBound
   * @param {Array|*} mixed
   * @param {Boolean} [convertLiteral]
   * @returns {LatLngBounds}
   */
  function toLatLngBound(mixed, convertLiteral) {
    if (isArray(mixed)) {
      return new gm.LatLngBounds({lat: mixed[2], lng: mixed[3]}, {lat: mixed[0], lng: mixed[1]});
    } else if (convertLiteral && !mixed.getCenter){
      return new gm.LatLngBounds({lat: mixed.south, lng: mixed.west}, {lat: mixed.north, lng: mixed.east});
    }
    return mixed;
  }

  /**
   * Create a custom overlay view
   * @param {Map} map
   * @param {Object} options
   * @returns {OverlayView}
   */
  function createOverlayView(map, options) {

    var GMOverlayView = gm.OverlayView;

    var $div = $(document.createElement("div"))
      .css({
        border: "none",
        borderWidth: 0,
        position: "absolute"
      })
      .append(options.content);

    options = extend({x: 0, y: 0}, options);

    if (options.position) {
      options.position = toLatLng(options.position, true);
    } else if (options.bounds) {
      options.bounds = toLatLngBound(options.bounds, true);
    }

    /**
     * Class OverlayView
     * @constructor
     */
    function OverlayView() {
      var self = this,
        listeners = [];

      GMOverlayView.call(self);
      self.setMap(map);

      function fromLatLngToDivPixel(latlng) {
        return self.getProjection().fromLatLngToDivPixel(latlng);
      }

      self.onAdd = function () {
        var panes = self.getPanes();
        panes.overlayMouseTarget.appendChild($div[0]);
      };

      if (options.position) {
        self.getPosition = function () {
          return options.position;
        };

        self.setPosition = function (latlng) {
          options.position = latlng;
          self.draw();
        };

        self.draw = function () {
          var ps = fromLatLngToDivPixel(options.position);
          $div.css({
            left: (ps.x + options.x) + 'px',
            top: (ps.y + options.y) + 'px'
          });
        };
      } else {
        self.getBounds = function () {
          return options.bounds;
        };

        self.setBounds = function (bounds) {
          options.bounds = bounds;
          self.draw();
        };

        self.draw = function() {
          var sw = fromLatLngToDivPixel(options.bounds.getSouthWest());
          var ne = fromLatLngToDivPixel(options.bounds.getNorthEast());

          $div.css({
            left: (sw.x + options.x) + 'px',
            top: (ne.y + options.y) + 'px',
            width: (ne.x - sw.x + options.x) + 'px',
            height: (sw.y - ne.y + options.y) + 'px'
          });
        };
      }

      self.onRemove = function () {
        listeners.map(function (handler) {
          gm.event.removeListener(handler);
        });
        $div.remove();
        self.$ = $div = null; // mem leaks
      };

      self.$ = $div;
    }

    OverlayView.prototype = new GMOverlayView();

    return new OverlayView();
  }

  /**
   * Return a map projection
   * @param {Map} map
   * @returns {*}
   */
  function getProjection(map) {
    function Overlay() {
      var self = this;
      self.onAdd = self.onRemove = self.draw = function () {};
      return gm.OverlayView.call(self);
    }
    Overlay.prototype = new gm.OverlayView();
    var overlay = new Overlay();
    overlay.setMap(map);
    return overlay.getProjection();
  }

  /**
   * Class used as event first parameter on clustering overlays
   * @param {Cluster} cluster
   * @param {Marker[]} markers
   * @param {OverlayView} overlay
   * @param {LatLngBounds} bounds
   * @constructor
   */
  function ClusterOverlay(cluster, markers, overlay, bounds) {
    var self = this;
    self.cluster = cluster;
    self.markers = markers;
    self.$ = overlay.$;
    self.overlay = overlay;

    overlay.getBounds = function () {
      return gmElement('LatLngBounds', bounds.getSouthWest(), bounds.getNorthEast());
    };
  }

  /**
   * Cluster Group definition.
   * @typedef {Object} ClusterGroupDef
   * @property {String|jQuery} content
   * @property {Number} [x] Offset
   * @property {Number} [y] Offset
   */

  /**
   * Cluster evaluation function
   * @callback clusterCallback
   * @param {Marker[]} markers
   * @return {ClusterGroupDef|undefined}
   */

  /**
   * Class used to handle clustering
   * @param {Map} map
   * @param {Object} options
   * @param {Integer} [options.size]
   * @param {Object[]} [options.markers] markers definition
   * @param {clusterCallback} [options.cb] callback used to evaluate clustering elements
   * @constructor
   */
  function Cluster(map, options) {
    var timer, igniter, previousViewHash, projection, filter,
      self = this,
      markers = [],
      radius = (options.size || 200) >> 1,
      enabled = true,
      overlays = {},
      handlers = [];

    options = options || {};
    options.markers = options.markers || [];

    /**
     * Cluster evaluation function
     * @callback bindCallback
     * @param {ClusterOverlay[]} instances
     */

    /**
     * Bind a function to each current or future overlays
     * @param {bindCallback} fn
     */
    self._b = function (fn) {
      fn(objectValues(overlays));
      handlers.push(fn);
    };

    /**
     * Get the marker list
     * @returns {Marker[]}
     */
    self.markers = function () {
      return slice(markers);
    };

    /**
     * Get the current groups
     * @returns {ClusterOverlay[]}
     */
    self.groups = function () {
      return objectValues(overlays);
    };

    /**
     * Enable the clustering feature
     */
    self.enable = function () {
      if (!enabled) {
        enabled = true;
        previousViewHash = '';
        delayRedraw();
      }
    };


    /**
     * Disable the clustering feature
     */
    self.disable = function () {
      if (enabled) {
        enabled = false;
        previousViewHash = '';
        delayRedraw();
      }
    };

    /**
     * Add a marker
     * @param {Marker} marker
     */
    self.add = function (marker) {
      markers.push(marker);
      previousViewHash = '';
      delayRedraw();
    };

    /**
     * Remove a marker
     * @param {Marker} marker
     */
    self.remove = function (marker) {
      markers = markers.filter(function (item) {
        return item !== marker;
      });
      previousViewHash = '';
      delayRedraw();
    };

    /**
     * Filtering function, Cluster only handle those who return true
     * @callback filterCallback
     * @param {Marker} marker
     * @returns {Boolean}
     */

    /**
     * Set a filter function
     * @param {filterCallback} fn
     */
    self.filter = function (fn) {
      if (filter !== fn) {
        filter = fn;
        previousViewHash = '';
        delayRedraw();
      }
    };

    /**
     * Generate extended visible bounds
     * @returns {LatLngBounds}
     */
    function extendsMapBounds() {
      var circle = gmElement('Circle', {
        center: map.getCenter(),
        radius: 1.15 * distanceInMeter(map.getCenter(), map.getBounds().getNorthEast()) // + 15%
      });
      return circle.getBounds();
    }

    /**
     * Generate bounds extended by radius
     * @param {LatLng} latLng
     * @returns {LatLngBounds}
     */
    function extendsBounds(latLng) {
      var p = projection.fromLatLngToDivPixel(latLng);
      return gmElement('LatLngBounds',
        projection.fromDivPixelToLatLng(gmElement('Point', p.x - radius, p.y + radius)),
        projection.fromDivPixelToLatLng(gmElement('Point', p.x + radius, p.y - radius))
      );
    }

    options.markers.map(function (opts) {
      opts.position = toLatLng(opts.position);
      markers.push(gmElement('Marker', opts));
    });

    /**
     * Redraw clusters
     */
    function redraw() {
      var keys, bounds, overlayOptions, hash, currentMarkers, viewHash,
        zoom = map.getZoom(),
        currentHashes = {},
        newOverlays = [],
        ignore = {};

      viewHash = '' + zoom;

      if (zoom > 3) {
        bounds = extendsMapBounds();
        foreach(markers, function (marker, index) {
          if (!bounds.contains(marker.getPosition())) {
            viewHash += '-' + index;
            ignore[index] = true;
            if (marker.getMap()) {
              marker.setMap(null);
            }
          }
        });
      }
      if (filter) {
        foreach(markers, function (marker, index) {
          if (!ignore[index] && !filter(marker)) {
            viewHash += '-' + index;
            ignore[index] = true;
            if (marker.getMap()) {
              marker.setMap(null);
            }
          }
        });
      }

      if (viewHash === previousViewHash) {
        return;
      }
      previousViewHash = viewHash;

      foreach(markers, function (marker, index) {
        if (ignore[index]) {
          return;
        }

        keys = [index];
        bounds = extendsBounds(marker.getPosition());

        if (enabled) {
          foreach(slice(markers, index + 1), function (marker, idx) {
            idx += index + 1;
            if (!ignore[idx] && bounds.contains(marker.getPosition())) {
              keys.push(idx);
              ignore[idx] = true;
            }
          });
        }

        hash = keys.join('-');
        currentHashes[hash] = true;

        if (overlays[hash]) { // hash is already set
          return;
        }

        currentMarkers = keys.map(function (key) {
          return markers[key];
        });

        // ask the user callback on this subset (may be composed by only one marker)
        overlayOptions = options.cb(slice(currentMarkers));

        // create an overlay if cb returns its properties
        if (overlayOptions) {
          bounds = gmElement('LatLngBounds');
          foreach(currentMarkers, function (marker) {
            bounds.extend(marker.getPosition());
            if (marker.getMap()) {
              marker.setMap(null);
            }
          });

          overlayOptions = dupOpts(overlayOptions);
          overlayOptions.position = bounds.getCenter();
          overlays[hash] = new ClusterOverlay(self, slice(currentMarkers), createOverlayView(map, overlayOptions), bounds);
          newOverlays.push(overlays[hash]);

        } else {
          foreach(currentMarkers, function (marker) {
            if (!marker.getMap()) { // to avoid marker blinking
              marker.setMap(map);
            }
          });
        }

      });

      // remove previous overlays
      foreach(objectKeys(overlays), function (key) {
        if (!currentHashes[key]) {
          overlays[key].overlay.setMap(null);
          delete overlays[key];
        }
      });

      if (newOverlays.length) {
        foreach(handlers, function (fn) {
          fn(newOverlays);
        });
      }
    }

    /**
     * Restart redraw timer
     */
    function delayRedraw() {
      clearTimeout(timer);
      timer = setTimeout(redraw, 100);
    }

    /**
     * Init clustering
     */
    function init() {
      gm.event.addListener(map, "zoom_changed", delayRedraw);
      gm.event.addListener(map, "bounds_changed", delayRedraw);
      redraw();
    }

    igniter = setInterval(function () {
      projection = getProjection(map);
      if (projection) {
        clearInterval(igniter);
        init();
      }
    }, 10);
  }

  /**
   * Configure google maps loading library
   * @param {string|object} options
   */
  $.gmap3 = function (options) {
    loadOptions = options;
  };

  /**
   * jQuery Plugin
   */
  $.fn.gmap3 = function (options) {
    var items = [];
    gm = window.google.maps; // once gmap3 is loaded, google.maps library should be loaded
    this.each(function () {
      var $this = $(this), gmap3 = $this.data("gmap3");
      if (!gmap3) {
        gmap3 = new Gmap3($this, options);
        $this.data("gmap3", gmap3);
      }
      items.push(gmap3);
    });

    return new Handler(this, items);
  };

  /**
   * Class Handler
   * Chainable objet which handle all Gmap3 items associated to all jQuery elements in the current command set
   * @param {jQuery} chain - "this" to return to maintain the jQuery chain
   * @param {Gmap3[]} items
   * @constructor
   */
  function Handler(chain, items) {
    var self = this;

    // Map all functions from Gmap3 class
    objectKeys(items[0]).forEach(function (name) {
      self[name] = function () {
        var results = [],
          args = slice(arguments);
        items.forEach(function (item) {
          results.push(item[name].apply(item, args));
        });
        return name === 'get' ? (results.length > 1 ? results : results[0]) : self;
      };
    });

    self.$ = chain;
  }

  /**
   * Class Gmap3
   * Handle a Google.maps.Map instance
   * @param {jQuery} $container - Element to display the map in
   * @param {Object} options - MapOptions
   * @constructor
   */
  function Gmap3($container, options) {
    var map,
      previousResults = [],
      promise = when(),
      self = this;

    function context() {
      return {
        $: $container,
        get: self.get
      };
    }

    /**
     * Attach events to instances
     * @param {Object } events
     * @param {Array|Object} instances
     * @param {array} [args] arguments to add
     * @param {Boolean} once
     */
    function attachEvents(events, instances, args, once) {
      var hasArgs = arguments.length > 3;
      if (!hasArgs) {
        once = args;
      }
      $.each(events, function (eventName, handlers) {
        foreach(instances, function (instance) {
          var isClusterOverlay = instance instanceof ClusterOverlay;
          var isDom = isClusterOverlay || (instance instanceof gm.OverlayView);
          var eventListener = isDom ? instance.$.get(0) : instance;
          gm.event['add' + (isDom ? 'Dom' : '') + 'Listener' + (once ? 'Once' : '')](eventListener, eventName, function (event) {
            foreach(handlers, function (handler) {
              if (isFunction(handler)) {
                if (isClusterOverlay) {
                  handler.call(context(), undefined /* marker */, instance, instance.cluster, event);
                } else if (hasArgs) {
                  var buffer = slice(args);
                  buffer.unshift(instance);
                  buffer.push(event);
                  handler.apply(context(), buffer);
                } else {
                  handler.call(context(), instance, event);
                }
              }
            });
          });
        });
      });
    }

    /**
     * Decorator to handle multiple call based on array of options
     * @param {Function} fn
     * @returns {Deferred}
     */
    function multiple(fn) {
      return function (options) {
        if (isArray(options)) {
          var instances = [];
          var promises = options.map(function (opts) {
            return fn.call(self, opts).then(function (instance) {
              instances.push(instance);
            });
          });
          return all(promises).then(function () {
            previousResults.push(instances);
            return instances;
          });
        } else {
          return fn.apply(self, arguments).then(function (instance) {
            previousResults.push(instance);
            return instance;
          });
        }
      };
    }

    /**
     * Decorator to chain promise result onto the main promise chain
     * @param {Function} fn
     * @returns {Deferred}
     */
    function chainToPromise(fn) {
      return function () {
        var args = slice(arguments);
        promise = promise.then(function (instance) {
          if (isFunction(args[0])) {
            // handle return as a deferred / promise to support both sync & async result
            return when(args[0].call(context(), instance)).then(function (value) {
              args[0] = value;
              return fn.apply(self, args);
            });
          }

          return when(fn.apply(self, args));
        });
        return promise;
      };
    }

    self.map = chainToPromise(function (options) {
      return map || resolveLatLng(options, 'center', function (opts) {
          map = gmElement('Map', $container.get(0), opts);
          previousResults.push(map);
          return map;
        });
    });

    // Space separated string of : separated element
    // (google.maps class name) : (latLng property name) : (add map - 0|1 - default = 1)
    foreachStr('Marker:position Circle:center InfoWindow:position:0 Polyline:path Polygon:paths', function (item) {
      item = item.split(':');
      var property = item[1] || '';
      self[item[0].toLowerCase()] = chainToPromise(multiple(function (options) {
        return (property.match(/^path/) ? resolveArrayOfLatLng : resolveLatLng)(options, property, function (opts) {
          if (item[2] !== '0') {
            opts.map = map;
          }
          return gmElement(item[0], opts);
        });
      }));
    });

    foreachStr('TrafficLayer TransitLayer BicyclingLayer', function (item) {
      self[item.toLowerCase()] = chainToPromise(function () {
        var instance = gmElement(item);
        previousResults.push(instance);
        instance.setMap(map);
        return instance;
      });
    });

    self.kmllayer = chainToPromise(multiple(function (options) {
      options = dupOpts(options);
      options.map = map;
      return when(gmElement('KmlLayer', options));
    }));

    self.rectangle = chainToPromise(multiple(function (options) {
      return resolveLatLngBounds(options, function (opts) {
        opts.map = map;
        return gmElement('Rectangle', opts);
      });
    }));

    self.overlay = chainToPromise(multiple(function (options) {
      function fn(opts) {
        return createOverlayView(map, opts);
      }

      options = dupOpts(options);
      return options.bounds ? resolveLatLngBounds(options, fn) : resolveLatLng(options, 'position', fn);
    }));

    self.groundoverlay = chainToPromise(function (url, bounds, options) {
      return resolveLatLngBounds({bounds: bounds}, function (opts) {
        options = dupOpts(options);
        options.map = map;
        var instance = gmElement('GroundOverlay', url, opts.bounds, options);
        previousResults.push(instance);
        return instance;
      });
    });

    self.styledmaptype = chainToPromise(function (styleId, styles, options) {
      var instance = gmElement('StyledMapType', styles, options);
      previousResults.push(instance);
      map.mapTypes.set(styleId, instance);
      return instance;
    });

    self.streetviewpanorama = chainToPromise(function (container, options) {
      return resolveLatLng(options, 'position', function (opts) {
        var instance = gmElement('StreetViewPanorama', $(container).get(0), opts);
        map.setStreetView(instance);
        previousResults.push(instance);
        return instance;
      });
    });

    self.route = chainToPromise(function (options) {
      var dfd = deferred();
      options = dupOpts(options);
      options.origin = toLatLng(options.origin);
      options.destination = toLatLng(options.destination);
      service('DirectionsService').route(options, function (results, status) {
        previousResults.push(results);
        dfd.resolve(status === gm.DirectionsStatus.OK ? results : false);
      });
      return dfd;
    });

    self.cluster = chainToPromise(function (options) {
      var cluster = new Cluster(map, dupOpts(options));
      previousResults.push(cluster);
      return resolved(cluster);
    });

    self.directionsrenderer = chainToPromise(function (options) {
      var instance;
      if (options) {
        options = dupOpts(options);
        options.map = map;
        if (options.panel) {
          options.panel = $(options.panel).get(0);
        }
        instance = gmElement('DirectionsRenderer', options);
      }
      previousResults.push(instance);
      return instance;
    });

    self.latlng = chainToPromise(multiple(function (options) {
      return resolveLatLng(options, 'latlng', function (opts) {
        previousResults.push(opts.latlng);
        return opts.latlng;
      });
    }));

    self.fit = chainToPromise(function () {
      var bounds = gmElement('LatLngBounds');
      foreach(previousResults, function (instances) {
        if (instances !== map) {
          foreach(instances, function (instance) {
            if (instance) {
              if (instance.getPosition && instance.getPosition()) {
                bounds.extend(instance.getPosition());
              } else if (instance.getBounds && instance.getBounds()) {
                bounds.extend(instance.getBounds().getNorthEast());
                bounds.extend(instance.getBounds().getSouthWest());
              } else if (instance.getPaths && instance.getPaths()) {
                foreach(instance.getPaths().getArray(), function (path) {
                  foreach(path.getArray(), function (latLng) {
                    bounds.extend(latLng);
                  });
                });
              } else if (instance.getPath && instance.getPath()) {
                foreach(instance.getPath().getArray(), function (latLng) {
                  bounds.extend(latLng);
                });
              } else if (instance.getCenter && instance.getCenter()) {
                bounds.extend(instance.getCenter());
              }
            }
          });
        }
      });
      if (!bounds.isEmpty()) {
        map.fitBounds(bounds);
      }
      return true;
    });

    self.wait = function (duration) {
      promise = promise.then(function (instance) {
        var dfd = deferred();
        setTimeout(function () {
          dfd.resolve(instance);
        }, duration);
        return dfd;
      });
    };

    self.then = function (fn) {
      if (isFunction(fn)) {
        promise = promise.then(function (instance) {
          return when(fn.call(context(), instance)).then(function (newInstance) {
            return isUndefined(newInstance) ? instance : newInstance;
          });
        });
      }
    };

    foreachStr('on once', function (name, once) {
      self[name] = function () {
        var events = arguments[0];
        if (events) {
          if (typeof events === 'string') { // cast call on('click', handler) to on({click: handler})
            events = {};
            events[arguments[0]] = slice(arguments, 1);
          }
          promise.then(function (instances) {
            if (instances) {
              if (instances instanceof Cluster) {
                instances._b(function (items) {
                  if (items && items.length) {
                    attachEvents(events, items, once);
                  }
                });
                return attachEvents(events, instances.markers(), [undefined, instances], once);
              }
              attachEvents(events, instances, once);
            }
          });
        }
      };
    });

    self.get = function (index) {
      if (isUndefined(index)) {
        return previousResults.map(function (instance) {
          return isArray(instance) ? instance.slice() : instance;
        });
      } else {
        if (index < 0) {
          index = previousResults.length + index;
        }
        return isArray(previousResults[index]) ? previousResults[index].slice() : previousResults[index];
      }
    };

    if (options) {
      self.map(options);
    }
  }

})(jQuery, window, document);