设置Map Pin背景色后首个AdvancedMarkerElement标记消失问题
问题解决方法
你遇到的问题核心是同一个DOM元素只能被添加到页面的一个位置。当你把pinBackground.element同时传给两个标记时,第二个标记会把这个DOM元素从第一个标记的DOM结构中移走,导致第一个标记失去内容,自然就不显示了。
要实现不同颜色的标记,正确的做法是给每个标记创建独立的PinElement实例:
// 第一个标记的独立背景 const pinBackground1 = new PinElement({ background: "#FBBC04", }); new google.maps.marker.AdvancedMarkerElement({ map, title: 'wittebergstudio', content: pinBackground1.element, position: { lat: -28.507, lng: 27.933 } }); // 第二个标记的独立背景(可设置不同颜色) const pinBackground2 = new PinElement({ background: "#34A853", }); new google.maps.marker.AdvancedMarkerElement({ map, title: 'rusendalcottages', content: pinBackground2.element, position: { lat: -28.506, lng: 27.940 } });
如果需要创建多个不同颜色的标记,还可以封装一个生成PinElement的函数,减少重复代码:
function createPinElement(color) { return new PinElement({ background: color, }); } // 创建第一个标记 new google.maps.marker.AdvancedMarkerElement({ map, title: 'wittebergstudio', content: createPinElement("#FBBC04").element, position: { lat: -28.507, lng: 27.933 } }); // 创建第二个标记 new google.maps.marker.AdvancedMarkerElement({ map, title: 'rusendalcottages', content: createPinElement("#34A853").element, position: { lat: -28.506, lng: 27.940 } });
这样每个标记都有自己独立的DOM元素,既不会出现覆盖消失的问题,还能轻松设置不同的标记颜色。
内容的提问来源于stack exchange,提问作者Theunis Prinsloo
相关产品推荐
相关产品推荐

