javascript - 谷歌地图标签放置

标签 javascript google-maps

我在谷歌地图中添加了label。但是 label 出现在 marker 的中间。我也尝试添加类,但 labelClass:"my_label" 在标签中,但类没有被添加。我无法定位 label

var marker = new google.maps.Marker({
  position: new google.maps.LatLng(-25.363882,131.044922),
  map: map,
  title:"Hello World!",
  icon: createMarker(25, 25, 4),
  labelClass:"my_label",
  labelAnchor: new google.maps.Point(15, 65),
  label:{
    text: 'My Place',
    color: '#000',
    fontSize:'14px',
    fontWeight:'bold'
  }
});

Fiddle Demo

enter image description here

如何在 google map labels 位于markers 的一侧。我想要这样。

最佳答案

要调整标签的位置,请使用 google.maps.Icon labelOrigin 属性:

icon: {
  url: createMarker(25, 25, 4),
  labelOrigin: new google.maps.Point(55, 12)
},

标签居中,因此您需要计算正确的偏移量以使其靠近标记(“x”坐标)。

proof of concept fiddle

screen shot of resulting map

代码片段:

var map = new google.maps.Map(document.getElementById("map_canvas"), {
  zoom: 16,
  center: new google.maps.LatLng(-25.363882, 131.044922),
  mapTypeId: google.maps.MapTypeId.ROADMAP
});

var marker = new google.maps.Marker({
  position: new google.maps.LatLng(-25.363882, 131.044922),
  map: map,
  title: "Hello World!",
  icon: {
    url: createMarker(25, 25, 4),
    labelOrigin: new google.maps.Point(55, 12)
  },
  label: {
    text: 'My Place',
    color: '#000',
    fontSize: '14px',
    fontWeight: 'bold'
  }
});

function createMarker(width, height, radius) {
  var canvas, context;
  canvas = document.createElement("canvas");
  canvas.width = width;
  canvas.height = height;
  context = canvas.getContext("2d");
  context.clearRect(0, 0, width, height);
  context.fillStyle = "rgba(255,255,0,1)";
  context.strokeStyle = "rgba(0,0,0,1)";
  context.beginPath();
  context.moveTo(radius, 0);
  context.lineTo(width - radius, 0);
  context.quadraticCurveTo(width, 0, width, radius);
  context.lineTo(width, height - radius);
  context.quadraticCurveTo(width, height, width - radius, height);
  context.lineTo(radius, height);
  context.quadraticCurveTo(0, height, 0, height - radius);
  context.lineTo(0, radius);
  context.quadraticCurveTo(0, 0, radius, 0);
  context.closePath();
  context.fill();
  context.stroke();
  return canvas.toDataURL();
}
html,
body,
#map_canvas {
  width: 100%;
  height: 100%;
  margin: 0;
  padding: 0px;
}
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="map_canvas"></div>

关于javascript - 谷歌地图标签放置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47434579/

相关文章:

javascript - 用 AMD 隐藏全局 window.google.maps 对象

javascript - 如何理解 `f(array[i], i, array)`源代码中的 `d3.min()`?

javascript - 控制不同消息的表单错误框宽度

使用 SetTimeout() 的 JavaScript Canvas 动画

google-maps - 适合 Google map 的图书馆吗?

google-maps - Google map -街景静态图像

javascript - 在 jQuery 中使用数组作为选择器

javascript - 如何绘制可以应对非常大数据量的 JavaScript 图表?

google-maps - Google map API getProjection() 在 V3 中不起作用

google-app-engine - 如何计算可视区域/边界框的geohash?