问题描述:

I have a series of locations returning in an array in JavaScript that I'm plotting on a Google Map.

I'm trying to change the type of marker icon depending the value on one of the array elements like so

for (i = 0; i < locations.length; i++) {

marker = new google.maps.Marker({

position: new google.maps.LatLng(locations[i][1], locations[i][2]),

map: map,

if (locations[i][3] == "Yes") {

console.log("yes")

} else {

console.log("no")

}

});

google.maps.event.addListener(marker, 'click', (function(marker, i) {

return function() {

infowindow.setContent(locations[i][0]);

infowindow.open(map, marker);

}

})(marker, i));

}

but running into

Uncaught SyntaxError: Unexpected token (

What am I missing?

网友答案:

What am I missing?

You're putting flow code in the middle of an object initializer:

for (i = 0; i < locations.length; i++) {
  marker = new google.maps.Marker({
    position: new google.maps.LatLng(locations[i][1], locations[i][2]),
    map: map,
    if (locations[i][3] == "Yes") {     // ====
      console.log("yes")                // ====
    } else {                            // ==== Here
      console.log("no")                 // ====
    }                                   // ====
  });

  google.maps.event.addListener(marker, 'click', (function(marker, i) {
    return function() {
      infowindow.setContent(locations[i][0]);
      infowindow.open(map, marker);
    }
  })(marker, i));
}

You can't do that. I'm not sure what you're trying to do there You've posted a clarifying comment:

within the new google.maps.Marker({ I need to be able to set icon: '/img/a.png' or icon: '/img/b.png' depending on the value of locations[i][3]

So my guess about a property was correct: You can do that with the conditional operator:

marker = new google.maps.Marker({
  position: new google.maps.LatLng(locations[i][1], locations[i][2]),
  map: map,
  icon: locations[i][3] == "Yes" ? '/img/a.png' : '/img/b.png'
});

...where the icon property's value will be '/img/a.png' if locations[i][3] == "Yes" is true, or '/img/b.png' if not.

相关阅读:
Top