Leaflet Many Markers
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.3.1/leaflet.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.3.1/leaflet.css">
<div id="visible">
</div>
<div id="map"></div>
CSS
html,
body {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
}
#map {
width: 100%;
height: 100%;
}
#visible {
position: absolute;
right: 10px;
top: 10px;
padding: 5px;
background: #FFF;
box-shadow: 0 0 3px rgba(0, 0, 0, 0.5);
z-index: 1000;
}
JavaScript
L.Marker.addInitHook(function() {
if (this.options.virtual) {
// setup virtualization after marker was added
this.on('add', function() {
this._updateIconVisibility = function() {
var map = this._map,
isVisible = map.getBounds().contains(this.getLatLng()),
wasVisible = this._wasVisible,
icon = this._icon,
iconParent = this._iconParent,
shadow = this._shadow,
shadowParent = this._shadowParent;
// remember parent of icon
if (!iconParent) {
iconParent = this._iconParent = icon.parentNode;
}
if (shadow && !shadowParent) {
shadowParent = this._shadowParent = shadow.parentNode;
}
// add/remove from DOM on change
if (isVisible != wasVisible) {
if (isVisible) {
iconParent.appendChild(icon);
if (shadow) {
shadowParent.appendChild(shadow);
}
} else {
iconParent.removeChild(icon);
if (shadow) {
shadowParent.removeChild(shadow);
}
}
this._wasVisible = isVisible;
}
};
// on map size change, remove/add icon from/to DOM
this._map.on('resize moveend zoomend', this._updateIconVisibility, this);
this._updateIconVisibility();
}, this);
}
});
var center = [47.39, 12.12];
var map = L.map('map');
map.setView([48.85, 2.35], 8);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);
for (var i = 0; i < 5000; i++) {
L.marker([-90 + 180 * Math.random(), -180 + 360 * Math.random()], {
virtual: false
}).addTo(map).bindPopup('marker ' + i);
}
map.on('resize moveend zoomend', function() {
var markers = document.querySelectorAll('#map .leaflet-marker-pane *');
var shadows = document.querySelectorAll('#map...