如何在AdvancedMarker中使用绝对路径的SVG图标?
问题
Google Maps的Marker已被弃用,正在迁移至AdvancedMarker。此前使用绝对路径SVG作为Marker的代码如下:
new google.maps.Marker({ position: loc, map: map, title: title, icon: '/img/marker.svg' });
迁移后尝试使用PinElement时,编写如下代码出现**"Failed to construct 'URL': Invalid URL"**错误:
const pinElement = new google.maps.marker.PinElement({ glyph: new URL('/img/marker.svg'), }); new google.maps.marker.AdvancedMarkerElement({ position: loc, map: map, title: title, content: pinElement });
需要不指定域名加载该绝对路径,因为项目部署在多个环境,域名会发生变化。
解决方案
直接将绝对路径字符串传给glyph参数即可,无需用new URL()构造URL对象——PinElement的glyph支持直接传入相对或绝对路径字符串,不需要手动封装成URL实例。修改后的代码如下:
const pinElement = new google.maps.marker.PinElement({ glyph: '/img/marker.svg', }); new google.maps.marker.AdvancedMarkerElement({ position: loc, map: map, title: title, content: pinElement });
如果后续需要动态处理路径,也可以借助当前页面的window.location.origin拼接完整URL,但当前场景下直接使用绝对路径字符串就足够适配多环境域名变化的需求。
内容的提问来源于stack exchange,提问作者Eric
相关产品推荐
相关产品推荐

