How do I use a button to animate a marker in leaflet?

Viewed 40

I have some code that creates a moving marker on leaflet, but need to use a button to animate it. This code is not working. The issue is that the button does not appear on the map. The code works if I change it to clicking on the marker.

<div id="map">
    <button id="animationButton">Start Animation</button>
</div>

<script>
    var map = L.map( 'map', {
        center: [ 13.022003264482255, 77.5671504709523 ],
        zoom: 15.8
    } );

    L.tileLayer( 'https://api.maptiler.com/maps/streets/{z}/{x}/{y}.png?key=96s2uc8tHryEc9jfNqir', {
        tileSize: 512,
        zoomOffset: -1,
        minZoom: 4,
        maxZoom: 30,
        crossOrigin: true
    } ).addTo( map );

    var marker = L.marker( [ 13.022130647492313, 77.56707655688966 ] ).addTo( map );
    var marker2 = L.marker( [ 13.023995226482452, 77.56490413181824 ] ).addTo( map );

    var button = document.getElementById( 'animationButton' ).addTo( map );

    button.on( 'click', function ( e ) {
        console.log( e )
        // var newMarker = L.marker([e.latlng.lat,e.latlng.lng]).addTo(map);
        var pos = map.latLngToLayerPoint( marker.getLatLng() )
        pos.y -= 25;
        var fx = new L.PosAnimation();

        fx.once( 'end', function () {
            pos.y += 25;
            fx.run( marker._icon, pos, 0.8 );
        } );

        fx.run( marker._icon, pos, 0.3 );
        L.Routing.control( {
            waypoints: [
                L.latLng( 13.022130647492313, 77.56707655688966 ),
                L.latLng( 13.023995226482452, 77.56490413181824 )
            ],
        } )
            .on( 'routesfound', function ( e ) {
                var routes = e.routes;
                console.log( routes );
                e.routes[ 0 ].coordinates.forEach( function ( coord, index ) {
                    setTimeout( function () {
                        marker.setLatLng( [ coord.lat, coord.lng ] );
                    }, 50 * index )
                } )
            } ).addTo( map );
    } )

</script>
1 Answers

Add this to your css to show the button on the map:

#animationButton {
    z-index: 1000;
    position: absolute;
}
Related