How to dynamically switch color with Leaflet's pulse icon

Viewed 1124

Given my code below, I have added a non-pulsing marker to my map, using L.icon.pulse:

m = L.geoJSON(metaFeatures, {
  pointToLayer: function (feature, latlng) {
    var pulsingIcon = L.icon.pulse({
      iconSize: [3, 3],
      color: color,
      fillColor: color,
      animate: false,
    });
    var pulseMarker = L.marker(coordinates, { icon: pulsingIcon });
    return pulseMarker;

    //...
  },
});

Later when I wish to change the animate:false to animate:true and change the color to red.

Note: if the marker was:

var circle = L.circleMarker(latlng, geojsonMarkerOptions);          

I would be able to do: layer.setStyle({fillColor:'blue'}); and that would solve the problem but since this is a L.Marker it cannot be done.

1 Answers

In Leaflet, instances of L.Marker don't have any .setStyle(), method, but they do have a .setIcon() method.

Therefore, you can create several instances of L.Icon and have your markers use one or the other, e.g.:

var map = new L.Map('leaflet', {
    layers: [
        new L.TileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
            'attribution': 'Map data © <a href="http://openstreetmap.org">OpenStreetMap</a> contributors'
        })
    ],
    center: [0, 0],
    zoom: 0
});

var blueIcon = L.icon.pulse({ color: "blue", fillColor: "blue", animate: false});
var redIcon = L.icon.pulse({ color: "red", fillColor: "red", animate: true});

var mymarker = L.marker([0,0], {icon: blueIcon}).addTo(map);

L.DomEvent.on(document.getElementById('change-to-red'), 'click', function(){
  mymarker.setIcon(redIcon);
})
#leaflet { min-height: 300px; }
<link type="text/css" rel="stylesheet" href="https://unpkg.com/leaflet/dist/leaflet.css" />
<link type="text/css" rel="stylesheet" href="https://unpkg.com/leaflet-pulse-icon@0.1.0/src/L.Icon.Pulse.css" />
<script src="https://unpkg.com/leaflet/dist/leaflet-src.js"></script>
<script src="https://unpkg.com/leaflet-pulse-icon@0.1.0/src/L.Icon.Pulse.js"></script>
<div id="leaflet"></div>
<button id='change-to-red'>Change to red!</button>

Related