简体   繁体   中英

Map markers are disappearing after a certain amount of toggle clicks

Very strange problem. I have items on a list. They toggle on click to expanded and collapse. When expanded, the items that show under it also appear as markers on a google map that I have on the page. In my test, I have one item on the list. As I click, the associated items underneath it show and their markers show on the map, or hide depending upon toggle state.

Consistently, after exactly 11 clicks of this item showing and hiding stuff on the map, one of the markers that is supposed to show no longer shows. I have no idea why it's exactly 11 clicks every time. Even stranger, if I drag or zoom on the map, the missing marker shows up right away. Because of that clue, I know where the problem is and I disabled it for now and the problem went away. Here's the associated code

function setNewMarkers() {
    //clearOldMarkers();
    bounds = new google.maps.LatLngBounds();
    for (i = 0; i < markers.length; i++) {
        markers[i].setMap(map);
        bounds.extend(markers[i].getPosition());
    }
    map.fitBounds(bounds);
    /*if (dragged == false && dblclick == false) {
        map.fitBounds(bounds);
        if (markers.length == 1) {
            map.setZoom(13);
        }
    }*/

}

notice the commented out section at the bottom. That was the problem and it went away after comment out. I was trying to prevent the map from zooming in too far if there is only one marker (home base marker) and all list items are collapsed. So I have to call fitBounds, but something is wrong with the way I am adjusting the zoom afterwards if there is only one marker , even though it works for 10 clicks.

So I am missing a subtlety and I think there is probably a better way to approach this that I am not aware of. Thx.

You are calling fitBounds twice when you have a single marker. Instead, you know what the center is (the one existing marker) and the zoom you want, just use those.

function setNewMarkers() {
  bounds = new google.maps.LatLngBounds();
  for (i = 0; i < markers.length; i++) {
    markers[i].setMap(map);
    bounds.extend(markers[i].getPosition());
  }
  map.fitBounds(bounds);
  if (dragged == false && dblclick == false) {
    if (markers.length == 1) {
        map.panTo(markers[0].getPosition());
        map.setZoom(13);
    }
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM