index.js (2897B)
1 import L from 'leaflet'; 2 3 import '~/lib/leaflet.hashState/leaflet.hashState'; 4 5 import './style.css'; 6 7 const Placemark = L.Marker.extend({ 8 initialize: function(latlng, title) { 9 this.title = title; 10 const icon = L.divIcon({ 11 html: '<div class="lealfet-placemark-title"></div>', 12 className: 'leaflet-placemark', 13 }); 14 L.Marker.prototype.initialize.call(this, latlng, {icon}); 15 }, 16 17 getTitle: function() { 18 return this.title; 19 }, 20 21 onAdd: function(map) { 22 L.Marker.prototype.onAdd.call(this, map); 23 this.getElement().children[0].innerHTML = this.title; 24 this.on('click', this.onClick, this); 25 map.on('click', this.onMapClick, this); 26 map.suggestedPoint = {latlng: this.getLatLng(), title: this.title}; 27 }, 28 29 onRemove: function(map) { 30 this._map.off('click', this.onMapClick, this); 31 this._map.suggestedPoint = null; 32 L.Marker.prototype.onRemove.call(this, map); 33 }, 34 35 onClick: function() { 36 this._map.fire('click', {latlng: this.getLatLng(), suggested: true}); 37 this._map.removeLayer(this); 38 }, 39 40 onMapClick: function(e) { 41 if (!e.suggested) { 42 this._map.removeLayer(this); 43 } 44 }, 45 }); 46 47 L.Map.include({ 48 showPlacemark: function(latlng, title) { 49 if (this._placemark) { 50 this.removeLayer(this._placemark); 51 } 52 this._placemark = new Placemark(latlng, title); 53 this.addLayer(this._placemark); 54 this.fire('placemarkshow'); 55 this._placemark.on('remove', this.onPlacemarkRemove, this); 56 }, 57 58 onPlacemarkRemove: function() { 59 this._placemark = null; 60 this.fire('placemarkhide'); 61 }, 62 }); 63 64 const PlacemarkHashStateInterface = L.Class.extend({ 65 includes: L.Mixin.HashState, 66 67 stateChangeEvents: ['placemarkshow', 'placemarkhide'], 68 69 initialize: function(map) { 70 this.map = map; 71 this.stateChangeEventsSource = 'map'; 72 }, 73 74 serializeState: function() { 75 const placemark = this.map._placemark; 76 if (!placemark) { 77 return null; 78 } 79 const latlng = placemark.getLatLng(); 80 return [latlng.lat.toFixed(6), latlng.lng.toFixed(6), encodeURIComponent(placemark.getTitle())]; 81 }, 82 83 unserializeState: function(values) { 84 if (!values) { 85 return false; 86 } 87 const lat = parseFloat(values[0]); 88 const lng = parseFloat(values[1]); 89 const title = decodeURIComponent(values[2] ?? ''); 90 if (isNaN(lat) || isNaN(lng) || lat < -90 || lat > 90 || lng < -180 || lng > 180) { 91 return false; 92 } 93 this.map.showPlacemark(L.latLng(lat, lng), title); 94 return true; 95 }, 96 }); 97 98 L.Map.include({ 99 getPlacemarkHashStateInterface: function() { 100 return new PlacemarkHashStateInterface(this); 101 }, 102 });