0

I'm using Leaflet MarkerCluster. It works fine, however, when you drill down to an individual marker (not cluster) I can't figure out how to replace the standard marker with my own custom icon/image.

1 Answer 1

4

You simply need to define a standard marker with your own icon, e.g. a PNG image, or alternatively with a L.circleMarker if you prefer a circle. You need to collect all markers on creation in an array without adding them to the map yet. You then add all markers to the marker clusterer, which you add in turn to the map.

Here is a simple example that should work, provided you have the MarkerClusterer files and your custom icon (my-icon.png) in the same directory:

<html>
<head>
  <link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.css" />
  <link rel="stylesheet" href="MarkerCluster.css" />
  <link rel="stylesheet" href="MarkerCluster.Default.css" />
  <script src="http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.js"></script>
  <script src="leaflet.markercluster.js"></script>
</head>
<body>
  <div id="map" style="width: 800px; height: 600px;">
  <script>
    var map = L.map('map', { maxZoom: 15 }).setView([48.5, 0.5], 10);
    L.tileLayer('http://{s}.mqcdn.com/tiles/1.0.0/map/{z}/{x}/{y}.png', {
      attribution: '&copy; <a href="http://osm.org/copyright" title="OpenStreetMap" target="_blank">OpenStreetMap</a> contributors | Tiles Courtesy of <a href="http://www.mapquest.com/" title="MapQuest" target="_blank">MapQuest</a> <img src="http://developer.mapquest.com/content/osm/mq_logo.png" width="16" height="16">',
          subdomains: ['otile1','otile2','otile3','otile4']
    }).addTo(map);
    var markers = [];
    var markerClusterer = L.markerClusterGroup({spiderfyDistanceMultiplier: 1.4});
    var myIcon = L.icon({
        iconUrl: 'my-icon.png',
        iconSize: [40, 40], iconAnchor: [20, 20], popupAnchor: [-20, -20]
    });
    var locations = [];
    for (var i=0; i < 1000; i++) { locations.push([Math.random()+48, Math.random()]); }
    for (var i=0; i < locations.length; i++){
      var m = L.marker([locations[i][0], locations[i][1]], { icon: myIcon });
      markers.push(m);
    }
    markerClusterer.addLayers(markers);
    map.addLayer(markerClusterer);
  </script>
</body>
</html>
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.