JavaScript

[JavaScript] OpenStreetMap 지도 위에 경로가 그려지는 애니메이션 출력

teamnova 2024. 11. 13. 12:00
728x90

안녕하세요,

 

오늘은 OpenStreetMap 지도 위에 원하는 경로를 따라 선이 그려지는 애니메이션을 출력해보도록 하겠습니다. 

 

애니메이션 효과를 주어 특정 경로의 출발점부터 도착점까지 위도, 경도를 따라 선이 그려지도록 하는 예제입니다. 

 

<!DOCTYPE html>  
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Leaflet OpenStreetMap 경로 출력 예제</title>
  <link rel="stylesheet" href="https://unpkg.com/leaflet@1.7.1/dist/leaflet.css" />
  <style>
    #map { height: 500px; width: 100%; }
  </style>
</head>
<body>

  <div id="map"></div> <!-- 지도가 표시될 요소 -->

  <script>
    // Leaflet를 사용한 지도 설정
    const map = L.map('map').setView([37.483759593241956, 126.97215914726259], 17); // 출발점 위치 및 줌 설정
    L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { // OSM 타일 추가
      attribution: OpenStreetMap contributors'
    }).addTo(map);

    // 선을 그릴 좌표 배열
    const testpath = [
  [37.483759593241956, 126.97215914726259],  [37.483636145811346, 126.97207063436511],
  [37.48356377998132, 126.97198748588563],  [37.483470129979594, 126.97188824415208],
  [37.48337860827358, 126.97179436683656],  [37.483278572792294, 126.97169512510303],
  [37.48338712192539, 126.97145640850069],  [37.48352334022225, 126.97115600109102],
  [37.48365955827075, 126.97089314460756],  [37.48377874885947, 126.97064369916919],
  [37.483848986081625, 126.9705042243004],  [37.48396391957549, 126.97061955928804],
  [37.48408736646454, 126.97074830532075],  [37.4842320970402, 126.97087168693544],
  [37.48434702994469,126.97099775075915],  [37.48441939501606,126.97105944156648],
  [37.484323617700696, 126.9712257385254], [37.484246995760024, 126.97137057781221],
  [37.48417037374073, 126.97151273489], [37.484095880035554, 126.97165489196779],
  [37.4840064874913,126.97178900241853],  [37.48394263560846,126.97189897298814],
  [37.48384685768194, 126.97201967239381],[37.483763850046266, 126.97214573621753]
];

const animatedPath = L.polyline([], {
      color: 'blue',   // 경로 색상
      weight: 8,       // 경로 두께
      opacity: 0.9     // 경로 투명도
    }).addTo(map);

    let index = 0; // 경로를 그릴 때 참조할 좌표 인덱스

    // 마커를 시작점에 추가
    const movingMarker = L.marker(testpath[0]).addTo(map);

    // 경로 그려지는 애니메이션 함수
    function animatePath() {
      if (index < testpath.length) {
        // 좌표를 하나씩 추가해 경로를 점진적으로 그림
        animatedPath.addLatLng(testpath[index]);
        // 마커의 위치를 경로의 끝점으로 이동
        movingMarker.setLatLng(testpath[index]);
        index++;
        setTimeout(animatePath, 100); // 100ms 간격으로 좌표를 추가
      }
    }

    // 경로 그리기 시작
    animatePath();
  </script>

</body>
</html>

 

 

시연 영상입니다.