selector.js (3351B)
1 import L from 'leaflet'; 2 3 import './selector.css'; 4 5 const RectangleSelect = L.Rectangle.extend({ 6 includes: L.Mixin.Events, 7 8 options: { 9 opacity: 1, 10 weight: 0.5, 11 fillOpacity: 0.2, 12 color: '#3388ff', 13 fillColor: '#3388ff', 14 15 }, 16 17 onAdd: function(map) { 18 L.Rectangle.prototype.onAdd.call(this, map); 19 this.markers = []; 20 for (let position of ['top', 'right', 'bottom', 'left']) { 21 let marker = L.marker([0, 0], { 22 icon: L.divIcon({className: `leaflet-rectangle-select-edge edge-${position}`}), 23 draggable: true 24 } 25 ) 26 .addTo(map); 27 marker.on({ 28 drag: this.onMarkerDrag, 29 dragend: this.onMarkerDragEnd 30 }, this 31 ); 32 this.markers[position] = marker; 33 } 34 this.placeMarkers(); 35 map.on('zoomend', this.placeMarkers, this); 36 }, 37 38 placeMarkers: function() { 39 const bounds = this.getBounds(); 40 const topLeftPixel = this._map.project(bounds.getNorthWest()); 41 const bottomRightPixel = this._map.project(bounds.getSouthEast()); 42 const size = bottomRightPixel.subtract(topLeftPixel); 43 let center = topLeftPixel.add(size.divideBy(2)); 44 center = this._map.unproject(center); 45 this.markers['top'].setLatLng([bounds.getNorth(), center.lng]); 46 this.markers['top']._icon.style.width = `${size.x}px`; 47 this.markers['top']._icon.style.marginLeft = `-${size.x / 2}px`; 48 this.markers['right'].setLatLng([center.lat, bounds.getEast()]); 49 this.markers['right']._icon.style.height = `${size.y}px`; 50 this.markers['right']._icon.style.marginTop = `-${size.y / 2}px`; 51 this.markers['bottom'].setLatLng([bounds.getSouth(), center.lng]); 52 this.markers['bottom']._icon.style.width = `${size.x}px`; 53 this.markers['bottom']._icon.style.marginLeft = `-${size.x / 2}px`; 54 this.markers['left'].setLatLng([center.lat, bounds.getWest()]); 55 this.markers['left']._icon.style.height = `${size.y}px`; 56 this.markers['left']._icon.style.marginTop = `-${size.y / 2}px`; 57 }, 58 59 onRemove: function(map) { 60 for (let marker of Object.values(this.markers)) { 61 this._map.removeLayer(marker); 62 } 63 this.markers = null; 64 map.off('zoomend', this.placeMarkers, this); 65 L.Rectangle.prototype.onRemove.call(this, map); 66 }, 67 68 setBoundsFromMarkers: function() { 69 this.setBounds( 70 [ 71 [this.markers['top'].getLatLng().lat, this.markers['left'].getLatLng().lng], 72 [this.markers['bottom'].getLatLng().lat, this.markers['right'].getLatLng().lng] 73 ] 74 ); 75 }, 76 onMarkerDrag: function() { 77 this.setBoundsFromMarkers(); 78 }, 79 80 onMarkerDragEnd: function() { 81 this.setBoundsFromMarkers(); 82 this.placeMarkers(); 83 this.fire('change'); 84 } 85 } 86 ); 87 88 export {RectangleSelect};
