Nate Nate - 24 days ago 19
Javascript Question

Marker Visibility Google Maps API

I have created 3 markers using Google Maps API, but I only want one marker to be active at a time because each marker represents a scoring sequence in a game. For example, if the score is 0 I only want the Chicago marker to be active. I am lost on how to do this any help would be great. Here is some of my code:

<script>
var map;
var score;
function initMap() {
var chicago = {lat: 41.8781, lng: -87.6298};
var indianapolis = {lat: 39.7684, lng: -86.1581};
var oklahomaCity = {lat: 35.4819, lng: -97.5084};

map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 0.0, lng: 0.0},
zoom: 1
});
var chicagoMarker = new google.maps.Marker({
position: chicago,
map: map

});

var oklahomaCityMarker = new google.maps.Marker({
position: oklahomaCity,
map:map
});

var indianapolisMarker = new google.maps.Marker({
position: indianapolis,
map:map

});


chicagoMarker.setVisible(false);
indianapolisMarker.setVisible(false);
oklahomaCityMarker.setVisible(false);
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCuvsCAF0gVmwv6AF0SoA3xBjV66RG4r7o&callback=initMap"
async defer></script>

Answer

Create the marker withoou map attribute and the assugn with setMap(map) only if socre is 0 var map;

    var score;
    function initMap() {
      var chicago = {lat: 41.8781, lng: -87.6298};
      var indianapolis = {lat: 39.7684, lng: -86.1581};
      var oklahomaCity = {lat: 35.4819, lng: -97.5084};

      map = new google.maps.Map(document.getElementById('map'), {
        center: {lat: 0.0, lng: 0.0},
        zoom: 1
      });
      var chicagoMarker = new google.maps.Marker({
          position: chicago
      });

      var oklahomaCityMarker = new google.maps.Marker({
          position: oklahomaCity
      });

      var indianapolisMarker = new google.maps.Marker({
          position: indianapolis
      });

      if ( score == 0) {
        chicagoMarker.setMap(map)
      }

  }
</script>
Comments