Leaflet OverlappingMarkers

by falkedesign

HTML

<link rel="stylesheet" href="https://unpkg.com/leaflet@1.6.0/dist/leaflet.css">
<script src="https://unpkg.com/leaflet@1.7.1/dist/leaflet.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/OverlappingMarkerSpiderfier-Leaflet/0.2.6/oms.min.js"></script>
<div id="map"></div>

CSS

#map {
    height: 500px;
    width: 80%;
}

JavaScript

// We’ll add a tile layer to add to our map, in this case it’s a OSM tile layer.
// Creating a tile layer usually involves setting the URL template for the tile images
var osmUrl = 'https://{s}.tile.osm.org/{z}/{x}/{y}.png',
    osmAttrib = '&copy; <a href="http://openstreetmap.org/copyright">OpenStreetMap</a> contributors',
    osm = L.tileLayer(osmUrl, {
      maxZoom: 18,
      attribution: osmAttrib
    });

// initialize the map on the "map" div with a given center and zoom
var map = L.map('map').setView([51.508, -0.11], 12).addLayer(osm);


//generate markers 
var baseJitter = 2.5;
var clusterJitterMax = 0.1;
var rnd = Math.random;
var data = [];
var clusterSizes = [1, 1, 2, 9, 24]; // change to get different cluster sizes
for (var i = 0; i < clusterSizes.length; i++) {
  var baseLon = -1 - baseJitter / 2 + rnd() * baseJitter;
  var baseLat = 52 - baseJitter / 2 + rnd() * baseJitter;
  var clusterJitter = clusterJitterMax * rnd();
  for (var j = 0; j < clusterSizes[i]; j ++) data.push({
    lon: baseLon - clusterJitter + rnd() * clusterJitter,
    lat: baseLat - clusterJitter + rnd() * clusterJitter
  });
}
var mapData = data;


var greenIcon = L.icon({
  iconUrl: 'https://leafletjs.com/examples/custom-icons/leaf-green.png',
  iconSize:     [38, 95], // size of the icon
  shadowSize:   [50, 64], // size of the shadow
  iconAnchor:   [22, 94], // point of the icon which will correspond to marker's location
  shadowAnchor: [4, 62],  // the same for the shadow
  popupAnchor:  [-3, -76] // point from which the popup should open relative to the iconAnchor
});

var oms = new OverlappingMarkerSpiderfier(map);

// add the gerated markers to the map
var bounds = new L.LatLngBounds();
for (var i = 0; i < mapData.length; i ++) {
  var loc = new L.LatLng(mapData[i].lat, mapData[i].lon);
  bounds.extend(loc);
  var marker = new L.Marker(loc);
  map.addLayer(marker);
  oms.addMarker(marker);
}
map.fitBounds(bounds);


// change icon of clicked...