1 ° --- In the action where the map is created, you must set OnCameraChangeListener and get the borders of the screen as follows:
mMap.setOnCameraChangeListener(new OnCameraChangeListener() { @Override public void onCameraChange(CameraPosition arg0) { LatLngBounds bounds = mapa.getProjection().getVisibleRegion().latLngBounds; }
2 ° --- This step may vary depending on how you retrieve the marker data. Basically, you need to calculate if the lat and length of each of your markers are inside the borders of the screen. I will show you how to do this by retrieving data from a SQLite database, storing latitud and longitude in two different DOUMLE clomuns inside the marker table.
mMap.setOnCameraChangeListener(new OnCameraChangeListener() { @Override public void onCameraChange(CameraPosition arg0) { LatLngBounds bounds = mMap.getProjection().getVisibleRegion().latLngBounds; LatLng northeast = bounds.northeast; String boundLat = String.valueOf(northeast.latitude); String boundLong = String.valueOf(northeast.longitude); LatLng southwest = bounds.southwest; String boundLat2 = String.valueOf(southwest.latitude); String boundLong2 = String.valueOf(southwest.longitude); //Remove all markers from map mMap.clear(); // or if your a using cluster manager: //mClusterManager.clearItems(); String[] fields = new String[] { "name", "latitude", "longitude" }; String[] args = new String[] {boundLat, boundLong, boundLat2, boundLong2,}; Cursor markers = dataBase.query("markers", fields, "latitude<=? AND longitude<=? AND latitude>=? AND longitude>=?"); if (markers.moveToFirst()) { do { mMap.addMarker(new MarkerOptions() .position(new LatLng(marker.getDouble(1), marker.getDouble(2))) .title(marker.getString(0)) ); // or if you are using cluster manager create and add the items as you normaly do. } while (c.moveToNext()); //if using cluster manager add : //mClusterManager.cluster(); } } });
The idea is quite simple, just keep in mind that your lat and longi markers should be less than the northeast position of your screen and larger than the southwest position, or just use the LatLngBounds.contains function.
Edition:
To avoid closing InfoWindow when clicking on a marker that is not yet in the center of the screen, you can change the default action for listening to a marker by deleting the camera movement.
map.setOnMarkerClickListener(new OnMarkerClickListener() { @Override public boolean onMarkerClick(Marker arg0) { arg0.showInfoWindow(); return true;
source share