3D 地圖的 Markers API 使用兩個類別來定義標記:Marker3DElement 類別提供基本參數 (position、label 和 map),PinElement 類別則包含進一步自訂的選項。
如要在地圖中加入標記,請先載入標記程式庫,其中提供 Marker3DElement 和 PinElement 類別。
下列程式碼片段說明如何建立新的 PinElement,然後套用至標記:
// Adjust the scale. const pinScaled = new PinElement({ scale: 1.5, }); const markerWithScale = new Marker3DElement({ position: { lat: 37.419, lng: -122.02 }, }); markerWithScale.append(pinScaled);
在使用 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 markerWithScale = new Marker3DElement({ position: { lat: 37.419, lng: -122.02 }, }); markerWithScale.append(pinScaled);
變更背景顏色
使用 PinElement.background 選項即可變更標記的背景顏色:
// Change the background color. const pinBackground = new PinElement({ background: '#FBBC04', }); const markerWithBackground = new Marker3DElement({ position: { lat: 37.419, lng: -122.01 }, }); markerWithBackground.append(pinBackground);
變更邊框顏色
使用 PinElement.borderColor 選項即可變更標記的邊框顏色:
// Change the border color. const pinBorder = new PinElement({ borderColor: '#FFFFFF', }); const markerWithBorder = new Marker3DElement({ position: { lat: 37.415, lng: -122.035 }, }); markerWithBorder.append(pinBorder);
變更字符顏色
使用 PinElement.glyphColor 選項即可變更標記的字符顏色:
// Change the glyph color. const pinGlyph = new PinElement({ glyphColor: 'white', }); const markerWithGlyphColor = new Marker3DElement({ position: { lat: 37.415, lng: -122.025 }, }); markerWithGlyphColor.append(pinGlyph);
在字符中加入文字
使用 PinElement.glyph 選項,將預設字符替換為文字字元。PinElement 的文字字符會隨著 PinElement 縮放,預設顏色則與 PinElement 的預設 glyphColor 一致:
// Change many elements together and extrude marker. const pinTextGlyph = new PinElement({ background: '#F0F6FC', glyphText: 'E', glyphColor: 'red', borderColor: '#0000FF', }); const markerWithGlyphText = new Marker3DElement({ position: { lat: 37.415, lng: -122.015, altitude: 50 }, extruded: true, altitudeMode: 'RELATIVE_TO_GROUND', }); markerWithGlyphText.append(pinTextGlyph);
變更高度
使用 Marker3DElement.position.altitude 選項搭配 Marker3DElement.altitudeMode 和 Marker3DElement.extruded,即可變更標記的高度,並在地面和標記之間加入延伸線:
// Change a marker's altitude and add an extrusion. const extrudedMarker = 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();