Google 地图不呈现带有文本节点的 SVG 元素

Google maps does not render SVG element with a text node

这是我的 SVG 元素:

<svg height="20" width="90" style="background-color: #eee; border-radius: 2px;">
  <text x="0" y="15" fill="#0052CC" font-weight="bold">&nbsp;Test</text>
</svg>

我试图让它显示为 google 地图标记,但它似乎不起作用。

这是我的标记对象:

var marker = new google.maps.Marker({
                position: location,
                map: map,
                icon: {
                  // anchor: new google.maps.Point(16, 16),
url: 'data:image/svg+xml;utf-8,' + 
'<svg height="20" width="90" style="background-color: #eee; border-radius: 2px;">' +
  '<text x="0" y="15" fill="#0052CC" font-weight="bold">&nbsp;Test</text>' + 
'</svg>',
  size: new google.maps.Size(32, 32),
  scaledSize: new google.maps.Size(20, 20)
                }
            });

示例 here 有效。看起来您缺少 xml 命名空间。这对我有用:

var marker = new google.maps.Marker({
  position: map.getCenter(),
  map: map,
  icon: {
    url: 'data:image/svg+xml;utf-8,' +
      '<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" height="20" width="90" style="background-color: #eee; border-radius: 2px;"><text x="0" y="15" fill="#0052CC" font-weight="bold">Test</text></svg>',
    size: new google.maps.Size(32, 32),
  }
});

proof of concept fiddle

代码片段:

html,
body,
#map {
  height: 100%;
  width: 100%;
  margin: 0;
  padding: 0;
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map"></div>
<script>
  function init() {
    var map = new google.maps.Map(document.getElementById('map'), {
      zoom: 17,
      center: new google.maps.LatLng(54.833890, 9.547270)
    });
    var marker = new google.maps.Marker({
      position: map.getCenter(),
      map: map,
      icon: {
        url: 'data:image/svg+xml;utf-8,' +
          '<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" height="20" width="90" style="background-color: #eee; border-radius: 2px;"><text x="0" y="15" fill="#0052CC" font-weight="bold">Test</text></svg>',
        size: new google.maps.Size(32, 32),
      }
    });
  }
  google.maps.event.addDomListener(window, 'load', init);
</script>