Get a list of markers in bounds of google map using markerclusterer v3

后端 未结 1 1299
耶瑟儿~
耶瑟儿~ 2021-02-04 10:00

I currently have a google map populated with data from a database. I am using markerclusterer v3 to cluster the markers to make the map load faster. I have scoured the docs and

相关标签:
1条回答
  • 2021-02-04 10:43
    1. Make your markers array global.
    2. Make your map variable global (or at least in scope).
    3. Run this code:

      for (var i=0; i < markers.length; i++) 
      {
          if (map.getBounds().contains(markers[i].getPosition()))
          {
              // markers[i] in visible bounds
          } 
          else 
          {
              // markers[i] is not in visible bounds
          }
      }
      

    Update: You may need to do this (if you are trying to add the loop to your init function). Other options (you haven't been real clear about why you want to do this):

    1. the marker test in your initial loop that adds the markers.
    2. to use addListenerOnce rather than addListener.
    3. you may want to re-render the "listOfItems" whenever the map is zoomed or panned (when the bounds changes again)

      var map = null;
      var markers = [];
      function init() 
      {
          var myOptions = 
          {
              zoom: 13,
              mapTypeId: google.maps.MapTypeId.ROADMAP
          };
          map = new google.maps.Map(document.getElementById("map"), myOptions);
          for (var i = 0; i < data.coords.length; i++) 
          {
              var dataInd = data.coords[i];
              var latLng = new google.maps.LatLng(dataInd[1],dataInd[2]);
              var marker = new google.maps.Marker({ position: latLng });        
              markers.push(marker);
              $('#listOfItems').append('<li>' + latlng + '</li>');
          }
      
          var markerCluster = new MarkerClusterer(map, markers);
      
          google.maps.event.addListener(map, 'bounds_changed', function() 
          {
              for (var i = 0; i < markers.length; i++) 
              {
                  if (map.getBounds().contains(markers[i].getPosition())) 
                  {
                      // markers[i] in visible bounds
                  } 
                  else 
                  {
                      // markers[i] is not in visible bounds
                  }
              }
          });
      }
      
      google.maps.event.addDomListener(window, 'load', init);
      
    0 讨论(0)
提交回复
热议问题