loot verge
loot verge

Reputation: 449

How to add label to Google map marker? (Error: InvalidValueError: setLabel: not a string; and no text property)

I want to add label to google map marker based on the number of my GPS locations. I got my data in my database I am able to add markers to my map but what I am unable to do is add markers inside the marker.

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
   });
}

Upvotes: 0

Views: 1529

Answers (2)

Madhvendra Singh
Madhvendra Singh

Reputation: 1

The value assigned to the label property in google map must be a string. in your code, it is currently assigning a number. please use something like this:

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

Upvotes: 0

geocodezip
geocodezip

Reputation: 161404

I get a javascript error with your code: InvalidValueError: setLabel: not a string; and no text property. The value assigned to the label property must be a string (or a MarkerLabel anonymous object). The code is currently assigning a number. Change:

var labels = i + 1;

to:

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

proof of concept fiddle

screenshot of resulting map

code snippet:

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>

Upvotes: 2

Related Questions