JSFiddle - React, Tailwind, and code Playground

by Lawrence Ross

HTML

<script src="https://maps.googleapis.com/maps/api/js"></script>
<button id="show">Show</button>
<button id="hide">Hide</button>
<div id="container"></div>

CSS

#container {
  width: 800px;
  height: 500px;
}

JavaScript

// Repeatedly click on 'Hide' then 'Show' (8+ times sometimes).  At some point the markers disappear and not come back - even if the code for showing/hiding markers is entirely commented out.
// The issue seems to be with the map.fitBounds() call when un-optimized markers are being used.
// Note - un-optimized markers are needed for targeting marker HTML elements as part of an acceptance test.
// Replicated on: 45.0.2 Firefox; 49.0.2623.112 m Chrome.

function changeBounds(boolToggle) {
  //return; // TODO - if you add this line in the problem is fixed.
  var bounds = new google.maps.LatLngBounds();
  var latLng = boolToggle ? new google.maps.LatLng(70, 70) : new google.maps.LatLng(30, 30);
  bounds.extend(marker1.getPosition());
  bounds.extend(marker2.getPosition());
  bounds.extend(latLng);
  map.fitBounds(bounds);
}

var mapOptions = {
  center: {
    lat: 50,
    lng: 50
  },
  zoom: 5,
};

var map = new google.maps.Map(document.getElementById("container"), mapOptions);

var marker1 = new google.maps.Marker({
  position: {
    lat: 51,
    lng: 51,
  },
  title: "MARK1",
  optimized: false
});

var marker2 = new google.maps.Marker({
  position: {
    lat: 52,
    lng: 52,
  },
  title: "MARK2",
  optimized: false
});

marker1.setMap(map);
marker2.setMap(map);

document.getElementById('show').onclick = function() {
  //marker1.setVisible(true); // TODO - The original code was showing/hiding the markers but the issue is replicated without even doing this.
  //marker2.setVisible(true);
  changeBounds(true);
}

document.getElementById('hide').onclick = function() {
  //marker1.setVisible(false); // TODO - The original code was showing/hiding the markers but the issue is replicated without even doing this.
  //marker2.setVisible(false);

  changeBounds(false);
}