0

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?

2
  • yeah, that does work but I should have been more specific: 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] Commented Feb 26, 2015 at 12:23
  • 1
    you can use self executing function like so jsbin.com/tacoro/2/edit?js,output, or use ternary operator jsbin.com/tacoro/3/edit?js,output Commented Feb 26, 2015 at 12:25

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I'm going to accept this on the basis of it being more succinct

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.