Google Apps Script 및 Leaflet.js를 사용하여 대화형 XY 이미지 플롯 구축

WBOY
풀어 주다: 2024-09-08 22:35:08
원래의
794명이 탐색했습니다.

Google Maps has a ton of features for plotting points on a map, but what if you want to plot points on an image? These XY Image Plot maps are commonly used for floor maps, job site inspections, and even games.

In this guide, I'll show you how to create an interactive map with draggable points using Leaflet.js and Google Apps Script. We'll cover everything from setting up the map to integrating data from Google Sheets, and deploying it as a web app.

This guide will cover:

  • Setting up Leaflet.js in a Google Apps Script HTML Service

  • Displaying Markers using data from Google Sheets

  • Updating Sheets row when a Marker is moved

  • Creating new Markers from the map and saving to Sheets

  • Deleting a marker from the web app

Setting up Leaflet.js in a Google Apps Script HTML Service

Leaflet.js is one of the most popular open-source mapping libraries. It's light-weight, easy to use, and had great documentation. They support a ton of different map types, including "CRS.Simple", or Coordinate Reference System, which allows you to supply a background image.

Google Sheets Set Up

Start out by creating a sheet named map_pin with the following structure:

id title x y
1 test1 10 30
2 test2 50 80

그런 다음 확장 메뉴에서 Apps Script를 엽니다.

HTML 파일 생성

먼저 라이브러리를 작동시키기 위해 Leaflet 문서의 기본 예제부터 시작하겠습니다. 여기의 빠른 시작 가이드에서 전체 예를 볼 수 있습니다.

Index라는 새 HTML 파일을 추가하고 콘텐츠를 다음으로 설정합니다.

<!DOCTYPE html>
<html>
<head>
  <title>Quick Start - Leaflet</title>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.3/dist/leaflet.css" />
  <style>
    #map {
      height: 400px;
    }
  </style>
</head>
<body>
  <div id="map"></div>

  <script src="https://unpkg.com/leaflet@1.9.3/dist/leaflet.js"></script>
  <script>
    var map = L.map('map').setView([40.73, -73.99], 13);

    L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
      maxZoom: 19,
      attribution: '© OpenStreetMap'
    }).addTo(map);

    var marker = L.marker([40.73, -73.99]).addTo(map)
      .bindPopup('Test Popup Message')
      .openPopup();
  </script>
</body>
</html>
로그인 후 복사

그런 다음 Code.gs 파일을 다음으로 업데이트하세요.

function doGet() {
  const html = HtmlService.createHtmlOutputFromFile('Index')
    .setTitle('Map with Draggable Points')
    .setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL);
  return html;
}
로그인 후 복사

저장한 다음 배포를 클릭하고 웹 앱으로 게시하세요. 그런 다음 새 배포에 대한 링크를 열면 Leaflet.js가 뉴욕 지도를 표시하는 것을 볼 수 있습니다.

Building an Interactive XY Image Plot with Google Apps Script and Leaflet.js

그럼 Leaflet을 사용한 일반 지도 예시입니다. 이제 배경 이미지를 제공할 수 있는 CRS.Simple 지도 유형을 살펴보겠습니다.

리플렛 튜토리얼의 예시로 HTML을 업데이트하세요.

<!DOCTYPE html>
<html>
<head>
  <title>CRS Simple Example - Leaflet</title>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.3/dist/leaflet.css" />
  <style>
    #map {
      height: 400px;
      width: 600px;
    }
    body {
      margin: 0;
      padding: 0;
    }
  </style>
</head>
<body>
  <div id="map"></div>

  <script src="https://unpkg.com/leaflet@1.9.3/dist/leaflet.js"></script>
  <script>
    // Set up the map with a simple CRS (no geographic projection)
    var map = L.map('map', {
      crs: L.CRS.Simple,
      minZoom: -1,
      maxZoom: 4
    });

    // Define the dimensions of the image
    var bounds = [[0, 0], [1000, 1000]];
    var image = L.imageOverlay('https://leafletjs.com/examples/crs-simple/uqm_map_full.png', bounds).addTo(map);

    // Set the initial view of the map to show the whole image
    map.fitBounds(bounds);

    // Optional: Add a marker or other elements to the map
    var marker = L.marker([500, 500]).addTo(map)
      .bindPopup('Center of the image')
      .openPopup();
  </script>
</body>
</html>
로그인 후 복사

여기에서는 1000 x 1000픽셀의 이미지를 제공하고 중앙 마커를 500, 500으로 설정합니다.

저장을 클릭한 다음 배포>배포 테스트를 클릭하여 새 지도 유형을 확인하세요. 이제 배경 이미지가 있는 지도와 중앙에 마커가 표시됩니다.

Building an Interactive XY Image Plot with Google Apps Script and Leaflet.js

Google 스프레드시트의 데이터로 지도 초기화

다음으로 시트의 데이터를 사용하여 지도에 일련의 마커를 채웁니다.

먼저 Code.gs 파일에 함수를 추가하여 마커 위치를 가져옵니다.

function getPinData(){
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const sh = ss.getSheetByName('map_pin');
  const data = sh.getDataRange().getValues();
  const json = arrayToJSON(data);
  //Logger.log(json);
  return json
}

function arrayToJSON(data=getPinData()){
  const headers = data[0];
  const rows = data.slice(1);
  let jsonData = [];
  for(row of rows){
    const obj = {};
    headers.forEach((h,i)=>obj[h] = row[i]);
    jsonData.push(obj)
  }
  //Logger.log(jsonData)
  return jsonData
}
로그인 후 복사

다음 섹션의 HTML에서 더 쉽게 작업할 수 있도록 핀을 JSON으로 반환합니다.

이제 이 JSON을 반복하고 지도가 로드된 후 지도 핀을 생성하는 함수를 HTML에 추가하세요.

// Add map pins from sheet data
    google.script.run.withSuccessHandler(addMarkers).getPinData();

    function addMarkers(mapPinData) {
      mapPinData.forEach(pin => {
        const marker = L.marker([pin.x, pin.y], {
          draggable: true
        }).addTo(map);

        marker.bindPopup(`<b>${pin.title}`).openPopup();

        marker.on('dragend', function(e) {
          const latLng = e.target.getLatLng();
          console.log(`Marker ${pin.title} moved to: ${latLng.lat}, ${latLng.lng}`);
        });
      });
    }
로그인 후 복사

저장한 다음 테스트 배포를 엽니다. 이제 시트 데이터에서 마커가 생성되었습니다!

Building an Interactive XY Image Plot with Google Apps Script and Leaflet.js

각 핀에는 해당 행의 제목이 포함된 팝업이 있습니다. 이 시점에서 핀을 드래그할 수 있지만 새 위치를 저장하는 기능이 여전히 필요합니다.

드래그 시 마커 위치 저장

새 위치를 저장하려면 클라이언트 측에서 이벤트를 캡처하는 HTML 함수와 서버 측 Code.gs 파일에 새 위치를 저장하는 함수 두 가지가 필요합니다.

다음을 사용하여 HTML을 업데이트하세요.

    function addMarkers(mapPinData) {
      mapPinData.forEach(pin => {
        const { id, title, x, y } = pin;
        const marker = L.marker([x, y], {
          draggable: true
        }).addTo(map);

        marker.bindPopup(`<b>${title}</b>`).openPopup();

        marker.on('dragend', function(e) {
          const latLng = e.target.getLatLng();
          console.log(`Marker ${title} moved to: ${latLng.lat}, ${latLng.lng}`);
          saveMarkerPosition({ id, title, lat: latLng.lat, lng: latLng.lng });
        });
      });
    }

    function saveMarkerPosition({ id, title, lat, lng }) {
      google.script.run.saveMarkerPosition({ id, title, lat, lng });
    }
로그인 후 복사

그런 다음 Code.gs 파일에 함수를 추가하여 위치를 저장합니다.

function saveMarkerPosition({ id, lat, lng }) {
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const sh = ss.getSheetByName('map_pin');
  const data = sh.getDataRange().getValues();

  for (let i = 1; i < data.length; i++) {
    if (data[i][0] === id) {  // ID column (index 0)
      sh.getRange(i + 1, 3).setValue(lat);  // latitude column
      sh.getRange(i + 1, 4).setValue(lng);  // longitude column
      break;
    }
  }
}
로그인 후 복사

테스트 배포를 저장하고 새로 고칩니다. 이제 마커를 드래그하면 시트 업데이트가 표시됩니다!

Building an Interactive XY Image Plot with Google Apps Script and Leaflet.js

새 포인트 추가

이제 기존 포인트를 이동할 수 있지만 새 포인트를 추가하는 것은 어떨까요? 이번에도 HTML과 Code.gs 파일에 각각 하나씩 두 개의 함수가 필요합니다.

먼저 사용자가 지도의 빈 곳을 클릭하면 프롬프트가 열리는 함수를 HTML에 추가하고 해당 값을 서버 함수에 전달합니다.

    // Function to add a new pin
    map.on('click', function(e) {
      const latLng = e.latlng;
      const title = prompt('Enter a title for the new pin:');
      if (title) {
        google.script.run.withSuccessHandler(function(id) {
          addNewMarker({ id, title, lat: latLng.lat, lng: latLng.lng });
        }).addNewPin({ title, lat: latLng.lat, lng: latLng.lng });
      }
    });

    function addNewMarker({ id, title, lat, lng }) {
      const marker = L.marker([lat, lng], {
        draggable: true
      }).addTo(map);

      marker.bindPopup(`<b>${title}</b>`).openPopup();

      marker.on('dragend', function(e) {
        const latLng = e.target.getLatLng();
        saveMarkerPosition({ id, title, lat: latLng.lat, lng: latLng.lng });
      });
    }
로그인 후 복사

그런 다음 Code.gs에 함수를 추가하여 새 행을 저장하세요.

function addNewPin({ title, lat, lng }) {
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const sh = ss.getSheetByName('map_pin');

  // Check if there are any rows present, if not initialize ID
  const lastRow = sh.getLastRow();
  let newId = 1;

  if (lastRow > 0) {
    const lastId = sh.getRange(lastRow, 1).getValue();
    newId = lastId + 1;
  }

  sh.appendRow([newId, title, lat, lng]);

  return newId;
}
로그인 후 복사

한 번 더 저장하고 테스트 배포를 새로 고칩니다. 이제 빈 곳을 클릭하면 제목을 입력하고 새 마커를 저장할 수 있습니다!

Building an Interactive XY Image Plot with Google Apps Script and Leaflet.js

마커 삭제

마지막으로 마커를 삭제하는 방법을 추가하여 지도 보기에서 완전한 CRUD 앱을 제공해야 합니다.

팝업에 삭제 버튼을 제공하도록 마커 추가 기능을 업데이트하세요.

      const popupContent = `<b>${title}</b><br><button onclick="deleteMarker(${id})">Delete Marker</button>`;
      marker.bindPopup(popupContent).openPopup();
로그인 후 복사

그런 다음 클라이언트 측에서 삭제하는 기능을 추가합니다.

// Function to delete a marker
  function deleteMarker(id) {
    const confirmed = confirm('Are you sure you want to delete this marker?');
    if (confirmed) {
      google.script.run.withSuccessHandler(() => {
        // Refresh the markers after deletion
        google.script.run.withSuccessHandler(addMarkers).getPinData();
      }).deleteMarker(id);
    }
  }
로그인 후 복사

그런 다음 Code.gs 파일에 일치 함수를 추가합니다.

function deleteMarker(id) {
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const sh = ss.getSheetByName('map_pin');
  const data = sh.getDataRange().getValues();

  for (let i = 1; i < data.length; i++) {
    if (data[i][0] === id) {  // ID column (index 0)
      sh.deleteRow(i + 1);  // Delete the row
      break;
    }
  }
}
로그인 후 복사

다음은 무엇입니까?

각 마커에 다른 데이터 포인트 추가, 동적 배경 이미지, 기타 클릭 및 드래그 상호 작용 등 여기에서 더 많은 작업을 수행할 수 있습니다. 게임을 만들 수도 있어요! 사용 사례에 대한 아이디어가 있나요? 아래에 댓글을 남겨주세요!

위 내용은 Google Apps Script 및 Leaflet.js를 사용하여 대화형 XY 이미지 플롯 구축의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:dev.to
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!