javascript - Google Maps API,添加带有标签的自定义 SVG 标记

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

最佳答案

使用 SymbollabelOrigin 属性

labelOrigin

Type: Point

The origin of the label relative to the origin of the path, if label is supplied by the marker. By default, the origin is located at (0, 0). The origin is expressed in the same coordinate system as the symbol's path. This property is unused for symbols on polylines.

代码片段:

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?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="map_canvas"></div>

关于javascript - Google Maps API,添加带有标签的自定义 SVG 标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33321440/

相关文章:

javascript - 选择第一个非空的 span 元素

javascript - 有没有办法在 JSDoc 中记录 `this` 的值?

javascript - 防止cookie被发送到服务器

java - Android 谷歌地图不断崩溃

javascript - 将 Google map API 与 Meteor.js 结合使用

javascript - Google map API - 格式化的电话号码在侧栏列表中显示为未定义

javascript - 无法获得 interact.js 拖放交互以使用 Bootstrap 元素

javascript - 使用谷歌的自动完成服务仅搜索(和输出)国家和/或城市

jquery - 如何减小信息窗口谷歌地图中箭头的大小

google-maps - Google Maps v3-标记和叠加图类型加载事件?