hosuaby / Leaflet.SmoothMarkerBouncing

Smooth animation of marker bouncing for Leaflet.
BSD 2-Clause "Simplified" License
147 stars 28 forks source link

Make marker bounce from external link #5

Closed ijcurtis closed 7 years ago

ijcurtis commented 7 years ago

How do I make a specific marker bounce when a related link is clicked.

I use this to add my markers

function addLeafletMapMarker(i,obj){
        marker = new L.marker([obj.lt,obj.lg],{icon:obj.icon, riseOnHover:true, id:i}).on('click', markerOnClick);

        marker.setBouncingOptions({
            bounceHeight : 60,   // height of the bouncing
            bounceSpeed  : 54,   // bouncing speed coefficient
        });

        markersLeaflet.addLayer(marker);
    }

And I have a table with related details. I would like to do something like..

<div onclick="bounceMarker(5)">Bounce me</div>

hosuaby commented 7 years ago

It's pretty easy to make individual marker bounce. The most important, is to store the reference to marker once it was created. In this example, we assume i to be integer variable. So we will put marker for the table line number i into array in position with number i.

// Global array to store created markers
var markers = [];

// If all markers have the same options of bouncing, it will be much better to
// define them like this. It impoves performance a lot !
L.Marker.setBouncingOptions({
  bounceHeight: 60,
  bounceSpeed: 54
});

function addLeafletMapMarker(i, obj){
  var marker = new L.marker(
    [ obj.lt, obj.lg ],
    {
      id: i,
      icon: obj.icon,
      riseOnHover: true
    }
  ).on('click', markerOnClick);

  // Add marker to global array
  markers[i] = marker;

  markersLeaflet.addLayer(marker);
}

// ... somewhere later in the code
function bounceMarker(i) {
  markers[i].bounce();
}

Please, note. Unless you absolutely need to have different bouncing options per marker, it will be much better to define them globally (like in this example).

Hope it will resolve your problem :) Best