How can I determine which of my markers are visible on my Google map?

Here is what I am trying to do. I have about 160 attractions. The user enters their address (zip code, full address, whatever) that I use Google for geocoding. Then I create a Google map centered around this point and add a marker for each of my interests on the map (using MarkerManager). So far so good.

I want to display a list of items next to the map corresponding to the displayed markers. When a user drags a window or zooms in or out, or something else, I want to update this list. If too many elements are displayed at once, I want to display a message to the user.

What is the best way to do this? I tried to add a listener to the MarkerManager so that when I change it, I can determine which markers are still displayed. However, the event does not seem to fire as I expected, i.e. When changing the displayed markers. In addition, I doubt that a cycle of more than 160+ such markers will be effective every time.

             GEvent.addListener(mgr, "changed", 
                function(bounds, markerCount) 
                {
                    var visibleBounds = map.getBounds();

                    for (var i = 0; i < gmarkers.length; i++) 
                    {
                        //alert(gmarkers[i].getPoint());
                        if (visibleBounds.containsLatLng(gmarkers[i].getLatLng())) {

                            // this will need to be replaced with an ajax call
                            // to get the details from the server
                            strHtml += "<div>Another item</div>";
                            count ++;
                        }
                    }
                    alert(count);
                });

What is the best way to do this?

The UPDATE . This code works, but the event only fires when the card moves a certain minimum distance. Therefore, if the user drags the map a short distance, the event does not seem to fire.

+3
source share
3 answers

"" , , , . MarkerManager , ( , , ).

+1

" ", , .

google.maps.event.addListener(map, 'idle', function() {
  var bounds = map.getBounds();
  ...
});
+1

To get all the markers first, you need to find the borders of the current viewport, then you need to loop all the markers and see if they are in this binding. The following is an example.

var bounds = map.getBounds ();

for(var i = 0; i < markers.length; i++){ // looping through my Markers Collection        
if(bounds.contains(markers[i].position))
 console.log("Marker"+ i +" - matched");
}
0
source

Source: https://habr.com/ru/post/1708125/


All Articles