고도 서비스

개요

고도 서비스는 해저 지형(음수 값 반환)을 포함하는 지표면 위치의 고도 데이터를 제공합니다. 사용자가 요청하는 정확한 위치의 정확한 고도 측정값을 Google이 보유하고 있지 않는 경우에는 가장 가까운 위치 4곳의 보간 평균 값을 반환합니다.

ElevationService 객체는 전 세계 위치의 고도 데이터를 쿼리할 수 있는 간단한 인터페이스를 제공합니다. 또한 경로를 따라 샘플링된 고도 데이터를 요청할 수도 있어, 이를 통해 경로를 따라 등거리 고도 변화를 계산할 수 있습니다. ElevationService 객체는 고도 요청을 받고 고도 데이터를 반환하는 Google 지도 API 고도 서비스와 통신합니다.

고도 서비스를 사용하여 하이킹 및 자전거 애플리케이션, 모바일 위치 지정 애플리케이션 또는 저해상도 측량 애플리케이션을 개발할 수 있습니다.

시작하기

Maps JavaScript API에서 고도 서비스를 사용하려면 먼저 Google Cloud 콘솔에서 Maps JavaScript API에 설정한 것과 동일한 프로젝트에서 Elevation API를 사용 설정해야 합니다.

사용 설정된 API의 목록을 보려면 다음 단계를 따르세요.

  1. Google Cloud 콘솔로 이동합니다.
  2. 프로젝트 선택 버튼을 클릭한 후 Maps JavaScript API를 위해 설정한 것과 동일한 프로젝트를 선택하고 열기를 클릭합니다.
  3. 대시보드의 API 목록에서 Elevation API를 찾습니다.
  4. 목록에 API가 표시되면 완료된 것입니다. API가 표시되지 않으면 API를 사용 설정하세요.
    1. 페이지 상단에서 API 사용 설정을 선택하여 라이브러리 탭을 표시합니다. 또는 왼쪽 사이드 메뉴에서 라이브러리를 선택합니다.
    2. Elevation API를 검색한 후 결과 목록에서 선택합니다.
    3. 사용 설정을 선택합니다. 과정이 완료되면 Elevation API대시보드의 API 목록에 표시됩니다.

가격 정보 및 정책

가격 정보

2018년 7월 16일부터 지도, 경로, 장소에 사용한 만큼만 지불하는 새로운 요금제가 도입되었습니다. JavaScript 고도 서비스 사용의 새로운 가격 및 사용량 한도에 대해 자세히 알아보려면 Elevation API의 사용량 및 결제를 참고하세요.

정책

Elevation 서비스는 Elevation API에 대해 설명된 정책에 따라 사용해야 합니다.

고도 요청

Google Maps API는 외부 서버를 호출해야 하므로 고도 서비스 액세스는 비동기식입니다. 따라서 요청 완료 시 실행할 콜백 메서드를 전달해야 합니다. 이 콜백 메서드에서 결과를 처리해야 합니다. 고도 서비스는 상태 코드(ElevationStatus) 및 개별 ElevationResult 객체의 배열을 반환합니다.

ElevationService는 다음 두 가지 유형의 요청을 처리합니다.

  • getElevationForLocations() 메서드를 사용한 별도의 위치 요청. 이 요청에는 LocationElevationRequest 객체를 사용하여 하나 이상의 위치 목록이 전달됩니다.
  • getElevationAlongPath() 메서드를 사용한 경로에 있는 일련의 연결된 지점의 고도 요청. 이 요청에는 PathElevationRequest 객체 내의 순서가 지정된 경로 꼭짓점의 집합이 전달됩니다. 경로를 따라 고도를 요청할 때는 해당 경로를 따라 추출하고자 하는 샘플의 수를 나타내는 매개변수도 전달해야 합니다.

각 메서드는 반환된 ElevationResultElevationStatus 객체를 처리하기 위한 콜백 메서드도 전달해야 합니다.

위치 고도 요청

LocationElevationRequest 객체 리터럴에는 다음 필드가 포함되어 있습니다.

{
  locations[]: LatLng
}

locations(필수)는 고도 데이터를 반환할 지구상의 위치를 정의합니다. 이 매개변수는 LatLng의 배열을 취합니다.

서비스 할당량을 초과하지만 않는 한 배열 내에 원하는 수의 좌표를 전달할 수 있습니다. 여러 좌표를 전달하는 경우 반환되는 데이터의 정확도가 단일 좌표에 대해 데이터를 요청할 경우보다 낮을 수도 있습니다.

샘플링된 경로 고도 요청

PathElevationRequest 객체 리터럴에는 다음 필드가 포함되어 있습니다.

{
  path[]: LatLng,
  samples: Number
}

아래는 이러한 필드에 대한 설명입니다.

  • path(필수)는 고도 데이터를 반환할 지구상의 경로를 정의합니다. path 매개변수는 두 개 이상의 LatLng 객체의 배열을 사용하여 두 개 이상의 순서가 지정된 {위도, 경도} 쌍의 집합을 정의합니다.
  • samples(필수)는 고도 데이터를 반환할, 경로에 있는 샘플 지점의 수를 지정합니다. samples 매개변수는 제공된 path를 경로에 있는 순서가 지정된 등거리 지점의 집합으로 나눕니다.

위치 지정 요청과 마찬가지로 path 매개변수는 경도 및 위도 값의 집합을 지정합니다. 하지만 위치 지정 요청과 달리 path는 순서가 지정된 꼭짓점의 집합을 지정합니다. 경로 요청은 꼭짓점의 고도 데이터를 반환하는 대신 경로의 길이를 따라 샘플링되며, 여기에서 각 샘플은 끝점을 포함하여 다른 샘플에서 같은 거리만큼 떨어져 있습니다.

고도 응답

각각의 유효한 요청에 대해 고도 서비스는 정의된 콜백에 ElevationStatus 객체와 함께 ElevationResult 객체의 집합을 반환합니다.

고도 상태

각 고도 요청은 콜백 함수 내에 ElevationStatus 코드를 반환합니다. status 코드에는 다음 값 중 하나가 포함됩니다.

  • OK - 서비스 요청이 성공적이었음을 나타냅니다.
  • INVALID_REQUEST - 서비스 요청의 형식이 잘못되었음을 나타냅니다.
  • OVER_QUERY_LIMIT - 요청자가 할당량을 초과했음을 나타냅니다.
  • REQUEST_DENIED - 서비스에서 요청이 완료되지 않았음을 나타냅니다. 잘못된 매개변수가 원인일 가능성이 큽니다.
  • UNKNOWN_ERROR - 알 수 없는 오류를 나타냅니다.

OK의 상태 코드를 검사하여 콜백이 성공했는지 확인해야 합니다.

고도 결과

성공 시 콜백 함수의 results 인수에 ElevationResult 객체의 집합이 포함됩니다. 이러한 객체에는 다음과 같은 요소가 포함됩니다.

  • 고도 데이터를 계산 중인 위치의 location 요소(LatLng 객체 포함). 경로 요청의 경우 location 요소 집합에 경로를 따라 샘플링된 지점이 포함됩니다.
  • 위치의 고도를 미터 단위로 나타내는 elevation 요소.
  • 고도가 보간된 데이터 점 사이의 최대 거리를 미터 단위로 나타내는 resolution 값. 해상도를 알 수 없는 경우에는 이 속성이 누락됩니다. 여러 지점이 전달되면 고도 데이터의 정밀도가 떨어지고 resolution 값이 커집니다. 특정 지점의 가장 정확한 고도 값을 구하려면 독립적으로 퀴리해야 합니다.

고도 예

다음 코드는 지도 클릭을 LocationElevationRequest 객체를 사용한 고도 요청으로 변환합니다.

TypeScript

function initMap(): void {
  const map = new google.maps.Map(
    document.getElementById("map") as HTMLElement,
    {
      zoom: 8,
      center: { lat: 63.333, lng: -150.5 }, // Denali.
      mapTypeId: "terrain",
    }
  );
  const elevator = new google.maps.ElevationService();
  const infowindow = new google.maps.InfoWindow({});

  infowindow.open(map);

  // Add a listener for the click event. Display the elevation for the LatLng of
  // the click inside the infowindow.
  map.addListener("click", (event) => {
    displayLocationElevation(event.latLng, elevator, infowindow);
  });
}

function displayLocationElevation(
  location: google.maps.LatLng,
  elevator: google.maps.ElevationService,
  infowindow: google.maps.InfoWindow
) {
  // Initiate the location request
  elevator
    .getElevationForLocations({
      locations: [location],
    })
    .then(({ results }) => {
      infowindow.setPosition(location);

      // Retrieve the first result
      if (results[0]) {
        // Open the infowindow indicating the elevation at the clicked position.
        infowindow.setContent(
          "The elevation at this point <br>is " +
            results[0].elevation +
            " meters."
        );
      } else {
        infowindow.setContent("No results found");
      }
    })
    .catch((e) =>
      infowindow.setContent("Elevation service failed due to: " + e)
    );
}

declare global {
  interface Window {
    initMap: () => void;
  }
}
window.initMap = initMap;

JavaScript

function initMap() {
  const map = new google.maps.Map(document.getElementById("map"), {
    zoom: 8,
    center: { lat: 63.333, lng: -150.5 },
    mapTypeId: "terrain",
  });
  const elevator = new google.maps.ElevationService();
  const infowindow = new google.maps.InfoWindow({});

  infowindow.open(map);
  // Add a listener for the click event. Display the elevation for the LatLng of
  // the click inside the infowindow.
  map.addListener("click", (event) => {
    displayLocationElevation(event.latLng, elevator, infowindow);
  });
}

function displayLocationElevation(location, elevator, infowindow) {
  // Initiate the location request
  elevator
    .getElevationForLocations({
      locations: [location],
    })
    .then(({ results }) => {
      infowindow.setPosition(location);
      // Retrieve the first result
      if (results[0]) {
        // Open the infowindow indicating the elevation at the clicked position.
        infowindow.setContent(
          "The elevation at this point <br>is " +
            results[0].elevation +
            " meters."
        );
      } else {
        infowindow.setContent("No results found");
      }
    })
    .catch((e) =>
      infowindow.setContent("Elevation service failed due to: " + e)
    );
}

window.initMap = initMap;
예시 보기

샘플 사용해 보기

다음 예에서는 좌표의 집합을 지정하여 다중선을 생성하고 Google Visualization API를 사용하여 경로를 따라 고도 데이터를 표시합니다. Google Common Loader를 사용하여 이 API를 로드해야 합니다. 고도 요청은 PathElevationRequest를 사용하여 생성됩니다.

TypeScript

// Load the Visualization API and the columnchart package.
// @ts-ignore TODO update to newest visualization library
google.load("visualization", "1", { packages: ["columnchart"] });

function initMap(): void {
  // The following path marks a path from Mt. Whitney, the highest point in the
  // continental United States to Badwater, Death Valley, the lowest point.
  const path = [
    { lat: 36.579, lng: -118.292 }, // Mt. Whitney
    { lat: 36.606, lng: -118.0638 }, // Lone Pine
    { lat: 36.433, lng: -117.951 }, // Owens Lake
    { lat: 36.588, lng: -116.943 }, // Beatty Junction
    { lat: 36.34, lng: -117.468 }, // Panama Mint Springs
    { lat: 36.24, lng: -116.832 },
  ]; // Badwater, Death Valley

  const map = new google.maps.Map(
    document.getElementById("map") as HTMLElement,
    {
      zoom: 8,
      center: path[1],
      mapTypeId: "terrain",
    }
  );

  // Create an ElevationService.
  const elevator = new google.maps.ElevationService();

  // Draw the path, using the Visualization API and the Elevation service.
  displayPathElevation(path, elevator, map);
}

function displayPathElevation(
  path: google.maps.LatLngLiteral[],
  elevator: google.maps.ElevationService,
  map: google.maps.Map
) {
  // Display a polyline of the elevation path.
  new google.maps.Polyline({
    path: path,
    strokeColor: "#0000CC",
    strokeOpacity: 0.4,
    map: map,
  });

  // Create a PathElevationRequest object using this array.
  // Ask for 256 samples along that path.
  // Initiate the path request.
  elevator
    .getElevationAlongPath({
      path: path,
      samples: 256,
    })
    .then(plotElevation)
    .catch((e) => {
      const chartDiv = document.getElementById(
        "elevation_chart"
      ) as HTMLElement;

      // Show the error code inside the chartDiv.
      chartDiv.innerHTML = "Cannot show elevation: request failed because " + e;
    });
}

// Takes an array of ElevationResult objects, draws the path on the map
// and plots the elevation profile on a Visualization API ColumnChart.
function plotElevation({ results }: google.maps.PathElevationResponse) {
  const chartDiv = document.getElementById("elevation_chart") as HTMLElement;

  // Create a new chart in the elevation_chart DIV.
  const chart = new google.visualization.ColumnChart(chartDiv);

  // Extract the data from which to populate the chart.
  // Because the samples are equidistant, the 'Sample'
  // column here does double duty as distance along the
  // X axis.
  const data = new google.visualization.DataTable();

  data.addColumn("string", "Sample");
  data.addColumn("number", "Elevation");

  for (let i = 0; i < results.length; i++) {
    data.addRow(["", results[i].elevation]);
  }

  // Draw the chart using the data within its DIV.
  chart.draw(data, {
    height: 150,
    legend: "none",
    // @ts-ignore TODO update to newest visualization library
    titleY: "Elevation (m)",
  });
}

declare global {
  interface Window {
    initMap: () => void;
  }
}
window.initMap = initMap;

JavaScript

// Load the Visualization API and the columnchart package.
// @ts-ignore TODO update to newest visualization library
google.load("visualization", "1", { packages: ["columnchart"] });

function initMap() {
  // The following path marks a path from Mt. Whitney, the highest point in the
  // continental United States to Badwater, Death Valley, the lowest point.
  const path = [
    { lat: 36.579, lng: -118.292 },
    { lat: 36.606, lng: -118.0638 },
    { lat: 36.433, lng: -117.951 },
    { lat: 36.588, lng: -116.943 },
    { lat: 36.34, lng: -117.468 },
    { lat: 36.24, lng: -116.832 },
  ]; // Badwater, Death Valley
  const map = new google.maps.Map(document.getElementById("map"), {
    zoom: 8,
    center: path[1],
    mapTypeId: "terrain",
  });
  // Create an ElevationService.
  const elevator = new google.maps.ElevationService();

  // Draw the path, using the Visualization API and the Elevation service.
  displayPathElevation(path, elevator, map);
}

function displayPathElevation(path, elevator, map) {
  // Display a polyline of the elevation path.
  new google.maps.Polyline({
    path: path,
    strokeColor: "#0000CC",
    strokeOpacity: 0.4,
    map: map,
  });
  // Create a PathElevationRequest object using this array.
  // Ask for 256 samples along that path.
  // Initiate the path request.
  elevator
    .getElevationAlongPath({
      path: path,
      samples: 256,
    })
    .then(plotElevation)
    .catch((e) => {
      const chartDiv = document.getElementById("elevation_chart");

      // Show the error code inside the chartDiv.
      chartDiv.innerHTML = "Cannot show elevation: request failed because " + e;
    });
}

// Takes an array of ElevationResult objects, draws the path on the map
// and plots the elevation profile on a Visualization API ColumnChart.
function plotElevation({ results }) {
  const chartDiv = document.getElementById("elevation_chart");
  // Create a new chart in the elevation_chart DIV.
  const chart = new google.visualization.ColumnChart(chartDiv);
  // Extract the data from which to populate the chart.
  // Because the samples are equidistant, the 'Sample'
  // column here does double duty as distance along the
  // X axis.
  const data = new google.visualization.DataTable();

  data.addColumn("string", "Sample");
  data.addColumn("number", "Elevation");

  for (let i = 0; i < results.length; i++) {
    data.addRow(["", results[i].elevation]);
  }

  // Draw the chart using the data within its DIV.
  chart.draw(data, {
    height: 150,
    legend: "none",
    // @ts-ignore TODO update to newest visualization library
    titleY: "Elevation (m)",
  });
}

window.initMap = initMap;
예시 보기

샘플 사용해 보기