3D 标记使用两个类来定义标记:3DMarkerElement 类提供基本参数(position、label 和 map),PinElement 类包含进一步自定义的选项。
如需向地图添加标记,您必须先加载标记库,该库提供了 3DMarkerElement 和 PinElement 类。
以下代码段展示了用于创建新 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.altitudeMode 和 Marker3DElement.extruded 结合使用,可更改标记的海拔,并在地面和标记之间添加一个 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();