自訂地圖標記動畫移動

範例展示

原始碼

copy
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>自訂地圖標記動畫移動 - Map8 Platform Documentation</title>
    <link rel="stylesheet" href="https://api.map8.zone/css/gomp.css?key=[YOUR_KEY_HERE]" />
    <style>
        #map{
            height: 400px;
            width: 100%;
        }
    </style>
</head>
<body>
    <div id="map"></div>

    <script type="text/javascript" src="https://api.map8.zone/maps/js/gomp.js?key=[YOUR_KEY_HERE]"></script>
    <script type="text/javascript">
            gomp.accessToken = '[YOUR_KEY_HERE]';
        var map = new gomp.Map({
            container: 'map', // 地圖容器 ID
            style: 'https://api.map8.zone/styles/go-life-maps-tw-style-std/style.json', // 地圖樣式檔案位置
            maxBounds: [[105, 15], [138.45858, 33.4]], // 台灣地圖區域
            center: [121.54885, 25.037853], // 初始中心座標,格式為 [lng, lat]
            zoom: 15.5, // 初始 ZOOM LEVEL; [0-20, 0 為最小 (遠), 20 ;最大 (近)]
            minZoom: 6, // 限制地圖可縮放之最小等級, 可省略, [0-19.99]
            maxZoom: 19.99, // 限制地圖可縮放之最大等級, 可省略 [0-19.99]
            attributionControl: false
        }).addControl(new gomp.AttributionControl({
            compact: false
        }));

    //此範例移動座標
    const coordinates = [
          [121.545144, 25.036061],
          [121.546018, 25.036039],
          [121.547071, 25.036024],
          [121.548122, 25.036009],
          [121.548135, 25.036405],
          [121.548148, 25.036793],
          [121.548161, 25.037189],
          [121.548223, 25.037262],
          [121.548274, 25.03722],
          [121.54833, 25.037182],
          [121.54839, 25.037149],
          [121.548452, 25.037122],
          [121.548518, 25.0371],
          [121.548585, 25.037084],
          [121.548716, 25.037073],
          [121.548776, 25.037069],
          [121.548774, 25.03575],
        ];

     // 宣告marker
     const marker = new gomp.Marker({color: '#338bf1'}) //裡面可以選擇marker顏色
      .setLngLat(coordinates[0])
      .addTo(map);

    // 設定動畫
    let i = 0;
    let prevTime = null;
    const speed = 0.0001;
    function animateMarker(time) {
      if (!prevTime) {
        prevTime = time;
      }
      const deltaTime = time - prevTime;
      const distance = speed * deltaTime;
      const lngLatStart_ = marker.getLngLat();
      const lngLatStart =[lngLatStart_.lng, lngLatStart_.lat];
      const lngLatEnd = coordinates[i];
      const bearing = turf.bearing(lngLatStart, lngLatEnd);
      const lngLatNew = turf.destination(lngLatStart, distance, bearing);
      marker.setLngLat(lngLatNew.geometry.coordinates);
      if (turf.distance(lngLatStart, lngLatNew) >= turf.distance(lngLatStart, lngLatEnd)) {
        i++;
        //重複路徑
        if (i >= coordinates.length) { 
          i = 0;
        }
      }
      prevTime = time;
      requestAnimationFrame(animateMarker);
    }
    // 開始
    requestAnimationFrame(animateMarker);
    </script>
</body>
</html>