自訂基本標記

3D 標記使用兩個類別來定義標記:3DMarkerElement 類別提供基本參數 (positionlabelmap),PinElement 類別則包含進一步自訂的選項。

如要在地圖中新增標記,您必須先載入標記程式庫,該程式庫會提供 3DMarkerElementPinElement 類別。

以下程式碼片段顯示建立新 PinElement 的程式碼,然後將其套用至標記:

const pinScaled = new PinElement({
  scale: 1.5,
});

const markerWithLabel = new Marker3DElement({
  position: { lat: 37.419, lng: -122.03 },
  label: 'Simple label'
});

在使用 HTML 建立的地圖中,標記的基本參數會使用 gmp-marker-3d HTML 元素宣告;任何使用 PinElement 類別的自訂項目都必須以程式輔助方式套用。為此,程式碼必須從 HTML 網頁擷取 gmp-marker-3d 元素。以下程式碼片段顯示用來查詢 gmp-marker-3d 元素集合的程式碼,然後逐一處理結果,以套用在 gmp-marker-3d 中宣告的自訂項目。

// Return an array of markers.
const markers = [...document.querySelectorAll('gmp-marker-3d')];

// Loop through the markers
for (let i = 0; i < markers.length; i++) {
  const pin = new PinElement({
      scale: 2.0,
  });

  markers[i].appendChild(pin.element);
}

本頁說明如何透過下列方式自訂標記:

縮放標記

如要調整標記的縮放比例,請使用 scale 選項:

// Adjust the scale.
const pinScaled = new PinElement({
  scale: 1.5,
});
const markerScaled = new Marker3DElement({
  map,
  position: { lat: 37.419, lng: -122.02 },
});

markerScaled.appendChild(pinScaled);

變更背景顏色

使用 PinElement.background 選項即可變更標記的背景顏色:

// Change the background color.
const pinBackground = new PinElement({
  background: '#FBBC04',
});
const markerBackground = new Marker3DElement({
  map,
  position: { lat: 37.419, lng: -122.01 },
});

markerBackground.appendChild(pinBackground);

變更邊框顏色

使用 PinElement.borderColor 選項即可變更標記的邊框顏色:

// Change the border color.
const pinBorder = new PinElement({
  borderColor: "#137333",
});
const markerBorder = new Marker3DElement({
  map,
  position: { lat: 37.415, lng: -122.035 },
});

markerBorder.appendChild(pinBorder);

變更字符顏色

使用 PinElement.glyphColor 選項即可變更標記的字符顏色:

// Change the glyph color.
const pinGlyph = new PinElement({
  glyphColor: "white",
});
const markerGlyph = new Marker3DElement({
  map,
  position: { lat: 37.415, lng: -122.025 },
});

markerGlyph.appendChild(pinGlyph);

為符號新增文字

使用 PinElement.glyph 選項,即可將預設字符替換為文字字元。PinElement 的文字字符會隨著 PinElement 縮放,且其預設顏色會與 PinElement 的預設 glyphColor 相符:

const pinTextGlyph = new PinElement({
  glyph: "T",
  glyphColor: "white",
});
const markerGlyphText = new Marker3DElement({
  map,
  position: { lat: 37.415, lng: -122.015 },
});

markerGlyphText.appendChild(pinTextGlyph);

變更高度

使用 Marker3DElement.position.altitude 選項搭配 Marker3DElement.altitudeModeMarker3DElement.extruded,即可變更標記的高度,並在地面和標記之間新增外推線:

const marker = new Marker3DElement({
  position: { lat: 37.4239163, lng: -122.0947209, altitude: 100 },
  altitudeMode: 'RELATIVE_TO_GROUND',
  extruded: true,
});

移除標記

使用 Marker3DElement.remove() 從地圖中移除標記:

const marker = document.querySelector('gmp-marker-3d');
marker.remove();

後續步驟