Advertisement
metalx1000

Open Street Maps Leaflet Move Marker with Tweens

Sep 5th, 2024 (edited)
160
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <!DOCTYPE html>
  2. <html lang="en">
  3.   <head>
  4.     <title></title>
  5.     <meta charset="utf-8">
  6.     <meta name="viewport" content="width=device-width, initial-scale=1">
  7.     <link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.css" />
  8.     <style>
  9. @media only screen and (min-width: 600px) {
  10.   body {
  11.     margin-right: 200px;
  12.     margin-left: 200px;
  13.     margin-top: 20px;
  14.   }
  15. }
  16.     #map {
  17.       height: 100%;
  18.     }
  19.  
  20.  
  21.     html, body {
  22.       height: 100%;
  23.       margin: 0px;
  24.     }
  25.     </style>
  26.   </head>
  27.  
  28.   <body>
  29.     <div id="map"> </div>
  30.   </body>
  31.   <script type="text/javascript" src="http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.js"></script>
  32.  
  33.   <script type="module">
  34.     import {Tween, Easing} from 'https://unpkg.com/@tweenjs/tween.js@23.1.3/dist/tween.esm.js'
  35.  
  36.   var zoom = 15;
  37.  
  38.   const coords = [
  39.     {lat: 26.1635173, lng: -81.5693298},
  40.     {lat: 26.1635273, lng: -81.5584298},
  41.     {lat: 26.1605273, lng: -81.5584298},
  42.     {lat: 26.1505273, lng: -81.5504298},
  43.     {lat: 26.1605273, lng: -81.5594298},
  44.     {lat: 26.1635173, lng: -81.5693298}
  45.   ]
  46.   var map = L.map('map').setView([coords[0].lat,coords[0].lng], zoom);
  47.  
  48.   L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', {
  49.     maxZoom: 19,
  50.     attribution: '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>'
  51.   }).addTo(map);
  52.  
  53.  
  54.   var marker = L.marker([coords[0].lat,coords[0].lng]).addTo(map);
  55.   var i = 0;
  56.  
  57.   moveMarker();
  58.  
  59.   function moveMarker(){
  60.     i++;
  61.  
  62.     if(i > coords.length){i=1};
  63.     let tween = new Tween(coords[0]); // Create a new tween that modifies 'coords'.
  64.     tween.to(coords[i], 1000) // Move over 5 seconds.
  65.     tween.easing(Easing.Quadratic.InOut) // Use an easing function to make the animation smooth.
  66.     tween.onUpdate(() => {
  67.       // Called after tween.js updates 'coords'.
  68.       let newLatLng = L.latLng(coords[0].lat,coords[0].lng);
  69.       marker.setLatLng(newLatLng);// move marker
  70.     })
  71.     tween.start(); // Start the tween immediately.
  72.       tween.onComplete(() =>{
  73.         moveMarker();
  74.       });
  75.     // Setup the animation loop.
  76.     function animate() {
  77.       tween.update()
  78.       requestAnimationFrame(animate)
  79.     }
  80.     requestAnimationFrame(animate)
  81.   }
  82.   </script>
  83. </html>
  84.  
  85.  
  86.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement