Google Maps API,添加标签

时间:2015-10-24 17:53:50

标签: javascript google-maps google-maps-api-3 svg

我试图在我的SVG标记中添加标签,并且我对文本相对于标记的位置有疑问,反之亦然。

这是我的图标:

  var clickIcon = {
      path: 'M8,0C3.400,0,0,3.582,0,8s8,24,8,24s8-19.582,8-24S12.418,0,8,0z M8,12c-2.209,0-4-1.791-4-4   s1.791-4,4-4s4,1.791,4,4S10.209,12,8,12z',
      fillColor: myRandomColor,
      fillOpacity: 1,
      strokeColor: myRandomColor,
      strokeWeight: 1
  };

这是我添加标记的地方:

  clickMarker = new google.maps.Marker({
  position: location,
  map: map,
  animation: google.maps.Animation.DROP,
  draggable: isDraggable,
  icon: clickIcon,
  label: {
      text: labels[labelIndex++ % labels.length],
      color: 'black',
      fontSize: '15px',
      fontWeight: 'bold'
  }
  });

请注意我只添加了相关代码,如果需要更多,请告诉我。如您所见,我无法对齐标签和标记。理想情况下,我想将它放在针圈内,但在针脚下方也能正常工作。提前谢谢。

enter image description here

1 个答案:

答案 0 :(得分:4)

使用Symbol

labelOrigin属性
  

labelOrigin

     

类型:点

     

标签的原点相对于路径的原点,如果标签由标记提供。默认情况下,原点位于(0,0)。原点表示在与符号路径相同的坐标系中。此属性不用于折线上的符号。

代码段

function initialize() {
  var map = new google.maps.Map(
    document.getElementById("map_canvas"), {
      center: new google.maps.LatLng(37.4419, -122.1419),
      zoom: 13,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });
  var clickIcon = {
    path: 'M8,0C3.400,0,0,3.582,0,8s8,24,8,24s8-19.582,8-24S12.418,0,8,0z M8,12c-2.209,0-4-1.791-4-4   s1.791-4,4-4s4,1.791,4,4S10.209,12,8,12z',
    fillColor: "#ff0000",
    fillOpacity: 1,
    strokeColor: "#ff0000",
    strokeWeight: 1,
    labelOrigin: new google.maps.Point(8, 10),
    anchor: new google.maps.Point(9, 35),
  };
  var clickMarker = new google.maps.Marker({
    position: map.getCenter(),
    map: map,
    // animation: google.maps.Animation.DROP,
    draggable: true,
    icon: clickIcon,
    label: {
      text: "A",
      color: 'black',
      fontSize: '15px',
      fontWeight: 'bold'
    }
  });
}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map_canvas {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map_canvas"></div>