Hide particular marker google maps api

2019-09-19 13:32发布

问题:

Using current code for google maps api i found on stackoverflow, i need to hide all markers except one clicked how can i do it?

Not even sure how to approach it?

I think it has to do with JS closures however not an expert on that.

<!DOCTYPE html>
    <html> 
    <head> 
      <meta http-equiv="content-type" content="text/html; charset=UTF-8" /> 
      <title>Google Maps Multiple Markers</title> 
      <script src="http://maps.google.com/maps/api/js?sensor=false" 
              type="text/javascript"></script>
    </head> 
    <body>
      
      <div id="map" style="width: 500px; height: 400px;"></div>
    
      <script type="text/javascript">
        var locations = [
          ['Bondi Beach', -33.890542, 151.274856, 4],
          ['Coogee Beach', -33.923036, 151.259052, 5],
          ['Cronulla Beach', -34.028249, 151.157507, 3],
          ['Manly Beach', -33.80010128657071, 151.28747820854187, 2],
          ['Maroubra Beach', -33.950198, 151.259302, 1]
        ];
    
        var map = new google.maps.Map(document.getElementById('map'), {
          zoom: 10,
          center: new google.maps.LatLng(-33.92, 151.25),
          mapTypeId: google.maps.MapTypeId.ROADMAP
        });
    
        var infowindow = new google.maps.InfoWindow();
    
        var marker, i;
    
        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
        });
    
          google.maps.event.addListener(marker, 'click', (function(marker, i) {
            return function() {
              infowindow.setContent(locations[i][0]);
              infowindow.open(map, marker);

              //hide marker clicked
              marker.setVisible(false);


            }
          })(marker, i));
        }

        function hide_some_markers() {
            alert("what to do here?");
        }

      </script>


    </body>
    </html>

EDIT: Currently on clicking marker it hides marker that was clicked, what i need to do is hide all markers except one that was clicked, when i click the map it should restore all hidden markers.

回答1:

If you want to hide the markers you can just call the :

marker.setVisible(false);

You can also remove them by using :

marker.setMap(null);

In your loop you are not keeping track of your created markers. You can push them to an array while creating and on the button click you can iterate through and hide all except the desired one.

var allMarkers = [];
//for loop
//your code
allMarkers.push(marker);
//end loop

Then in your hide function, just iterate through all the markers and hide all except the desired one. like allMarkers[index].setVisible(false);