0

我在 JavaScript 的谷歌地图 API 中将自定义标记显示为 .svg。

谷歌地图 api 似乎不喜欢#00492C在代码中使用。fill="#0000"不起作用,只会fill="green"起作用。

var icon: {
        url: 'data:image/svg+xml;utf-8, \
              <svg width="30" height="48" viewBox="1 -10 60 78" xmlns="http://www.w3.org/2000/svg"> \
              <path fill="#00492C" d="M53.1,48.1c3.9-5.1,6.3-11.3,6.3-18.2C59.4,13.7,46.2,0.5,30,0.5C13.8,0.5,0.6,13.7,0.6,29.9 c0,6.9,2.5,13.1,6.3,18.2C12.8,55.8,30,77.5,30,77.5S47.2,55.8,53.1,48.1z"></path> \
              </svg>'
    }

我期待我的标记变成深绿色,但它不再出现了。

4

1 回答 1

3

您需要转义 # 字符,因为它是为URL 中片段标识符的开头保留的。用 %23 替换所有出现的 #

icon: {
    url: 'data:image/svg+xml;utf-8, \
          <svg width="30" height="48" viewBox="1 -10 60 78" xmlns="http://www.w3.org/2000/svg"> \
          <path fill="%2300492C" d="M53.1,48.1c3.9-5.1,6.3-11.3,6.3-18.2C59.4,13.7,46.2,0.5,30,0.5C13.8,0.5,0.6,13.7,0.6,29.9 c0,6.9,2.5,13.1,6.3,18.2C12.8,55.8,30,77.5,30,77.5S47.2,55.8,53.1,48.1z"></path> \
          </svg>'
}

概念证明小提琴

结果地图的屏幕截图

代码片段:

function initMap() {
  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 4,
    center: {
      lat: -33,
      lng: 151
    }
  });
  var beachMarker = new google.maps.Marker({
    position: {
      lat: -33.890,
      lng: 151.274
    },
    map: map,
    icon: {
      url: 'data:image/svg+xml;utf-8, \
              <svg width="30" height="48" viewBox="1 -10 60 78" xmlns="http://www.w3.org/2000/svg"> \
              <path fill="%2300492C" d="M53.1,48.1c3.9-5.1,6.3-11.3,6.3-18.2C59.4,13.7,46.2,0.5,30,0.5C13.8,0.5,0.6,13.7,0.6,29.9 c0,6.9,2.5,13.1,6.3,18.2C12.8,55.8,30,77.5,30,77.5S47.2,55.8,53.1,48.1z"></path> \
              </svg>'
    }
  });
}
html,
body,
#map {
  height: 100%;
  margin: 0;
  padding: 0;
}
<div id="map"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap">
</script>

于 2019-08-09T08:53:07.537 回答