简体   繁体   中英

Google Maps (v3) filter by map movement

I have a store locator that displays stores as markers on the map and lists them in a sidebar. There are ~600 stores and they are all loaded at once on the page load via AJAX. So I have access to all them in an array at all times. Now, the functionality I want is that when the user moves/zooms around in the viewport, I get the bounds of the current area being displayed and filter the results in the sidebar (the array of locations, each location has a lat and long) based on whether or not they would be in that area being displayed. Then I would draw the markers of the relevant locations. Basically, whatever locations would be viewable in the viewport would also be listed in the sidebar, staying in sync.

Could someone point me in the right direction to implement this? Does this even sound like an efficient way of handling this functionality?

You need to write a handler for bounds_changed event (more documentation here )

google.maps.event.addListener(map, 'bounds_changed', function(){
  // your logic here - map.getBounds() will give you the updated bounds
});

As for efficiency, loading everything at once is probably not the most scalable approach. What if you have 6000 stores next year or you add additional data for every store? A better approach is to pass the bounds back to the server using an AJAX call and only return stores that fall into the area.

You can attach moves/zooms event to the map and basically do a bound check to hide/show markers within the viewing bound. You can achieve this using LatLngBounds(sw?:LatLng, ne?:LatLng) and check the markers LatLng against the map's current bounds using getBounds(); . Furthermore within LatLngBounds there's a method to check to see if the LatLtn is within Bounds contains(latLng:LatLng) . So you would loop through your markers' LatLng and check against it.

Google Map API LatLngBounds

and

Google Map API Map

As far as the sidebar goes, if you have markers saved then you can just remove or hide the associated locations on the sidebar.

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