Phần tử độ cao

Phần tử độc lập về độ cao

ElevationElement là một phần tử HTML hiển thị trực quan dữ liệu độ cao cho một điểm hoặc một đường nhiều đoạn. Biểu đồ này cho thấy độ cao dọc theo đường dẫn được đặt trong thuộc tính path với một mảng gồm các toạ độ vĩ độ và kinh độ. Các đoạn thẳng được nội suy giữa các điểm của mảng, vì vậy, ngay cả khi có một số lượng nhỏ điểm, bạn vẫn sẽ tạo ra được một biểu đồ độ cao chi tiết.

Đặt độ cao của đường đi bằng toạ độ

Ví dụ sau đây kết xuất độ cao của một đường dẫn giữa hai điểm do một tập hợp toạ độ chọn, bằng cách sử dụng phần tử gmp-elevation.

Phần tử này được định cấu hình để đo lường bằng chỉ số bằng cách sử dụng thuộc tính unit-system:

  <gmp-elevation unit-system="metric"></gmp-elevation>

querySelector được dùng để chọn phần tử độ cao và đặt thuộc tính path bằng toạ độ (vĩ độ và kinh độ):

/** Maps JS loaded callback */
async function init() {
  // Load the Elevation Element from Maps JS
  const {ElevationElement} = await google.maps.importLibrary('elevation');

  // Specify an elevation path to render
  const elevationElement = document.querySelector('gmp-elevation');
  elevationElement.path = [
    {lat: 37.4523, lng: -122.2645},
    {lat: 37.377, lng: -122.4078},
  ];
}

Xem ví dụ đầy đủ về đoạn mã

JavaScript

/** Maps JS loaded callback */
async function init() {
  // Load the Elevation Element from Maps JS
  const {ElevationElement} = await google.maps.importLibrary('elevation');

  // Specify an elevation path to render
  const elevationElement = document.querySelector('gmp-elevation');
  elevationElement.path = [
    {lat: 37.4523, lng: -122.2645},
    {lat: 37.377, lng: -122.4078},
  ];
}

init();

CSS

html, body {
  margin: 0;
  padding: 0;
}

gmp-elevation {
  width: 100%;
  height: 100%;
}

.overlay {
  margin: 20px;
  width: 400px;
}

HTML

<!DOCTYPE html>
<html>
  <head>
    <title>Simple Elevation</title>
    <meta charset="utf-8">
    <link rel="stylesheet" type="text/css" href="style.css">
  </head>
  <body>
    <h1>Path elevation</h1>
        <div class="overlay">
          <gmp-elevation unit-system="metric"></gmp-elevation>
        </div>
    <script>
      (g=>{var h,a,k,p="The Google Maps JavaScript API",c="google",l="importLibrary",q="__ib__",m=document,b=window;b=b[c]||(b[c]={});var d=b.maps||(b.maps={}),r=new Set,e=new URLSearchParams,u=()=>h||(h=new Promise(async(f,n)=>{await (a=m.createElement("script"));e.set("libraries",[...r]+"");for(k in g)e.set(k.replace(/[A-Z]/g,t=>"_"+t[0].toLowerCase()),g[k]);e.set("callback",c+".maps."+q);a.src=`https://maps.${c}apis.com/maps/api/js?`+e;d[q]=f;a.onerror=()=>h=n(Error(p+" could not load."));a.nonce=m.querySelector("script[nonce]")?.nonce||"";m.head.append(a)}));d[l]?console.warn(p+" only loads once. Ignoring:",g):d[l]=(f,...n)=>r.add(f)&&u().then(()=>d[l](f,...n))})({
        key: "YOUR_API_KEY",
        v: "alpha"
      });
    </script>
  </body>
</html>

Đặt độ cao của đường bằng một đường nhiều đoạn

Ví dụ sau đây kết xuất độ cao của một đường dựa trên đường nhiều đoạn do người dùng vẽ. Nó lấy path từ đường nhiều đoạn của người dùng bằng cách sử dụng polyline.getPath().getArray():

      elevationElem.path = polyline.getPath().getArray();

Xem ví dụ đầy đủ về đoạn mã

JavaScript

const map = document.querySelector('gmp-map');
const elevationElem = document.querySelector('gmp-elevation');

async function init() {
  await google.maps.importLibrary('places');
  await google.maps.importLibrary('marker');
  await google.maps.importLibrary('elevation');


  map.innerMap.setOptions({'mapTypeControl': true, 'clickableIcons': false});

  findCurrentLocation();
  drawPolyline();
}

async function drawPolyline() {
  const {DrawingManager} = await google.maps.importLibrary('drawing');
  const drawingManager = new DrawingManager({
    drawingMode: google.maps.drawing.OverlayType.POLYLINE,
    drawingControl: true,
    drawingControlOptions: {
      position: google.maps.ControlPosition.TOP_CENTER,
      drawingModes: [google.maps.drawing.OverlayType.POLYLINE]
    },
    polylineOptions: {geodesic: true, strokeColor: '#5491f5', strokeWeight: 6}
  });

  drawingManager.setMap(map.innerMap);

  drawingManager.addListener('polylinecomplete', (polyline) => {
    console.log('complete');
    console.log(polyline.getPath().getArray());
    elevationElem.path = polyline.getPath().getArray();
    polyline.addListener('click', (e) => {
      console.log(e);
    });
  });
}

async function findCurrentLocation() {
  const {LatLng} = await google.maps.importLibrary('core');
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(
        (position) => {
          const pos =
              new LatLng(position.coords.latitude, position.coords.longitude);
          map.innerMap.panTo(pos);
          map.innerMap.setZoom(16);
        },
        () => {
          console.log('The Geolocation service failed.');
          map.innerMap.setZoom(16);
        },
    );
  } else {
    console.log(`Your browser doesn't support geolocation`);
    map.innerMap.setZoom(16);
  }
}

init();

CSS

html, body {
    height: 100%;
    margin: 0;
}

body {
    display: flex;
    flex-direction: column;
    font-family: Arial, Helvetica, sans-serif;
}

h1 {
    font-size: 16px;
    text-align: center;
}

gmp-map {
    box-sizing: border-box;
    margin-top: 20px;
    width: 100%;
    height: 100%;
}

gmp-elevation {
    width: 100%;
    height: 300px;
}

.overlay {
    width: 800px;
}

HTML

<!DOCTYPE html>
<html>
  <head>
    <title>Path Elevation</title>
    <meta charset="utf-8">
    <link rel="stylesheet" type="text/css" href="style.css">
  </head>
  <body>
    <h1>Draw polyline and get path elevation</h1>
    <gmp-map center="-37.813,144.963" zoom="12" map-id="DEMO_MAP_ID">
        <div id="elevation-container" class="overlay" slot="control-block-end-inline-center">
          <gmp-elevation unit-system="metric"></gmp-elevation>
        </div>
    </gmp-map>
    <script>
      (g=>{var h,a,k,p="The Google Maps JavaScript API",c="google",l="importLibrary",q="__ib__",m=document,b=window;b=b[c]||(b[c]={});var d=b.maps||(b.maps={}),r=new Set,e=new URLSearchParams,u=()=>h||(h=new Promise(async(f,n)=>{await (a=m.createElement("script"));e.set("libraries",[...r]+"");for(k in g)e.set(k.replace(/[A-Z]/g,t=>"_"+t[0].toLowerCase()),g[k]);e.set("callback",c+".maps."+q);a.src=`https://maps.${c}apis.com/maps/api/js?`+e;d[q]=f;a.onerror=()=>h=n(Error(p+" could not load."));a.nonce=m.querySelector("script[nonce]")?.nonce||"";m.head.append(a)}));d[l]?console.warn(p+" only loads once. Ignoring:",g):d[l]=(f,...n)=>r.add(f)&&u().then(()=>d[l](f,...n))})({
        key: "YOUR_API_KEY",
        v: "alpha"
      });
    </script>
  </body>
</html>