模型

模型是 3D 素材資源,可新增至場景來代表物件。Maps JavaScript API 中的擬真成像 3D 地圖支援加入 gLTF 模型。您可以縮放及旋轉這些模型,讓模型進一步自訂。

模型必須支援 glTF PBR 的核心屬性。不支援任何擴充功能或擴充功能屬性。

新增模型

Model3DElement 建構函式會採用一組 Model3DElementOptions 來指定模型的 LatLng 座標,以及一組參數來支援模型定位。

模型支援下列選項:

  • position:以 LatLng 座標表示的模型位置。
  • orientation:模型座標系統的旋轉角度。系統會按照下列順序套用旋轉:擲骰子、傾斜和方向。
  • scale:在其座標空間縮放模型。預設值為 1
  • altitudeModeposition 中表示高度的解讀方式。
  • src:模型的網址。

下例示範如何在地圖中加入模型,並使用可用的自訂選項修改模型:

async function init() {
  const { Map3DElement, MapMode, Model3DElement } = await google.maps.importLibrary("maps3d");

  const map = new Map3DElement({
    center: {lat: 37.7438, lng: -121.5088, altitude: 1800},
    heading: -90,
    tilt: 90,
    mode: MapMode.SATELLITE,
  });

  document.body.append(map);
  
  const models = [
    // A model with regular settings.
    {
      position: {lat: 37.76, lng: -121.63, altitude: 0},
      orientation: {tilt: 270},
    },
    // Scaled down model.
    {
      position: {lat: 37.75, lng: -121.63, altitude: 0},
      orientation: {tilt: 270},
      scale: 0.8,
    },
    // Scaled up model.
    {
      position: {lat: 37.735, lng: -121.63, altitude: 0},
      orientation: {tilt: 270},
      scale: 1.2,
    },
    // A model with an additional transformation applied.
    {
      position: {lat: 37.72, lng: -121.63, altitude: 0},
      orientation: {tilt: 270, roll: 90},
    },
    // Non-clamped to the ground model.
    {
      position: {lat: 37.71, lng: -121.63, altitude: 1000},
      altitudeMode: 'RELATIVE_TO_GROUND',
      orientation: {tilt: 270},
    },
  ];

  for (const {position, altitudeMode, orientation, scale} of models) {
    const model = new Model3DElement({
      src: 'https://storage.googleapis.com/maps-web-api.appspot.com/gltf/windmill.glb',
      position,
      altitudeMode,
      orientation,
      scale,
    });

    map.append(model);
  }
}

init();

新增互動模型

這些模型也支援互動。下例會在點選時變更模型的縮放比例

async function init() {
  const { Map3DElement, MapMode, Model3DInteractiveElement } = await google.maps.importLibrary("maps3d");

  const map = new Map3DElement({
    center: {lat: 37.7438, lng: -121.5088, altitude: 1800},
    heading: -90,
    tilt: 90,
    mode: MapMode.SATELLITE,
  });

  document.body.append(map);

  const model = new Model3DInteractiveElement({
    src: 'https://storage.googleapis.com/maps-web-api.appspot.com/gltf/windmill.glb',
    position: {lat: 37.76, lng: -121.63, altitude: 0},
    scale: 1.0,
  });

  model.addEventListener('gmp-click', (event) => {
    model.scale = (Math.random() * (1 - 2)).toFixed(2);

  });

  map.append(model);
}

init();