如何在Google地图标记中添加标签? (错误:InvalidValueError:setLabel:不是字符串;也没有text属性)

时间:2018-09-03 01:38:50

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

我想根据我的GPS位置数量向Google地图标记添加标签。我将数据存储在数据库中,可以在地图上添加标记,但是我无法做的是在标记内添加标记。

for(var i = 0; i < data.length; i++) {
   var coords = data[i].GPSCoordinates.split(',');
   var position = new google.maps.LatLng(coords[0], coords[1]);
   var labels = i + 1;
   addMarker(position, map, labels);
}

function addMarker(location, map, label) {
   var marker = new google.maps.Marker({
       position: location,
       map: map,
       label: label
   });
}

2 个答案:

答案 0 :(得分:2)

我收到您的代码InvalidValueError: setLabel: not a string; and no text property的JavaScript错误。分配给label property的值必须是字符串(或MarkerLabel匿名对象)。该代码当前正在分配一个数字。更改:

var labels = i + 1;

收件人:

var labels = ""+ (i + 1);

proof of concept fiddle

screenshot of resulting map

代码段:

function initialize() {
  var map = new google.maps.Map(
    document.getElementById("map_canvas"), {
      center: new google.maps.LatLng(37.4419, -122.1660756),
      zoom: 13,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });
  var data = [{GPSCoordinates: "37.4419, -122.1419"},
    {GPSCoordinates: "37.4529598, -122.1817252"},
    {GPSCoordinates: "37.4335499, -122.2030209"},
    {GPSCoordinates: "37.424106, -122.1660756"}
  ]
  for (var i = 0; i < data.length; i++) {
    var coords = data[i].GPSCoordinates.split(',');
    var position = new google.maps.LatLng(coords[0], coords[1]);
    var labels = "" + (i + 1);
    addMarker(position, map, labels);
  }

  function addMarker(location, map, label) {
    var marker = new google.maps.Marker({
      position: location,
      map: map,
      label: label
    });
  }
}
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>

答案 1 :(得分:0)

在Google地图中分配给label属性的值必须是字符串。在您的代码中,它当前正在分配一个数字。 请使用这样的内容:

var labels = (i+1).toString()