适用于 3D 地图的 Markers API 使用两个类来定义标记:3DMarkerElement 类提供基本参数(position、label 和
map),而 PinElement 类包含用于进一步自定义的选项。
如需向地图添加标记,您必须先加载标记库,该库提供 3DMarkerElement 和 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();