模型

選取平台: Android iOS JavaScript

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

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

新增模型

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

模型支援下列選項:

  • position:以 LatLng 座標表示的模型位置。
  • orientation:模型座標系統的旋轉角度。系統會依下列順序套用旋轉效果:側傾、傾斜,然後是航向。
  • scale:在座標空間中縮放模型。預設值為 1
  • altitudeMode:如何解讀以 position 表示的海拔高度。
  • 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();