L.Map.Sync.js 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. /*
  2. * Extends L.Map to synchronize the interaction on one map to one or more other maps.
  3. */
  4. (function () {
  5. 'use strict';
  6. L.Map = L.Map.extend({
  7. sync: function (map, options) {
  8. this._initSync();
  9. options = options || {};
  10. // prevent double-syncing the map:
  11. var present = false;
  12. this._syncMaps.forEach(function (other) {
  13. if (map === other) {
  14. present = true;
  15. }
  16. });
  17. if (!present) {
  18. this._syncMaps.push(map);
  19. }
  20. if (!options.noInitialSync) {
  21. map.setView(this.getCenter(), this.getZoom(), {
  22. animate: false,
  23. reset: true
  24. });
  25. }
  26. return this;
  27. },
  28. // unsync maps from each other
  29. unsync: function (map) {
  30. var self = this;
  31. if (this._syncMaps) {
  32. this._syncMaps.forEach(function (synced, id) {
  33. if (map === synced) {
  34. self._syncMaps.splice(id, 1);
  35. }
  36. });
  37. }
  38. return this;
  39. },
  40. // overload methods on originalMap to replay on _syncMaps;
  41. _initSync: function () {
  42. if (this._syncMaps) {
  43. return;
  44. }
  45. var originalMap = this;
  46. this._syncMaps = [];
  47. L.extend(originalMap, {
  48. setView: function (center, zoom, options, sync) {
  49. if (!sync) {
  50. originalMap._syncMaps.forEach(function (toSync) {
  51. toSync.setView(center, zoom, options, true);
  52. });
  53. }
  54. return L.Map.prototype.setView.call(this, center, zoom, options);
  55. },
  56. panBy: function (offset, options, sync) {
  57. if (!sync) {
  58. originalMap._syncMaps.forEach(function (toSync) {
  59. toSync.panBy(offset, options, true);
  60. });
  61. }
  62. return L.Map.prototype.panBy.call(this, offset, options);
  63. },
  64. _onResize: function (event, sync) {
  65. if (!sync) {
  66. originalMap._syncMaps.forEach(function (toSync) {
  67. toSync._onResize(event, true);
  68. });
  69. }
  70. return L.Map.prototype._onResize.call(this, event);
  71. }
  72. });
  73. originalMap.on('zoomend', function () {
  74. originalMap._syncMaps.forEach(function (toSync) {
  75. toSync.setView(originalMap.getCenter(), originalMap.getZoom(), {
  76. animate: false,
  77. reset: false
  78. });
  79. });
  80. }, this);
  81. originalMap.dragging._draggable._updatePosition = function () {
  82. L.Draggable.prototype._updatePosition.call(this);
  83. var self = this;
  84. originalMap._syncMaps.forEach(function (toSync) {
  85. L.DomUtil.setPosition(toSync.dragging._draggable._element, self._newPos);
  86. toSync.fire('moveend');
  87. });
  88. };
  89. }
  90. });
  91. })();