Google maps does not render SVG element with a text node

This is my SVG element :

<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>

I am trying to get it to display as a google map marker but it doesn't seem to be working.

This is my marker object :

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)
                }
            });

1 answer

  • answered 2018-10-11 21:08 geocodezip

    The example here works. Looks like you are missing the xml namespace. This works for me:

    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

    screenshot of resulting map

    code snippet:

    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>