Search code examples
androidgoogle-mapsscreen-size

Display markers in maps on android in the region that is displayed to me on my screen


I am working with Google Maps. Let's say I have around 1 million position markers stored in my database. What I want to do is load or display only those markers that should be on the part of map that is currently shown on screen. (For example, if my map is showing Asia, it should only show markers that are in Asia; if I move to any other place on the map, it should show markers in that region.) I'm doing this so I don't have to load the entire database at once, since that can cause delays in the app. I tried using Spatialite, but I didn't find a good tutorial, or information on how to use it. This is one of the links I followed, but I didn't get a good idea. Is there any other way to do this, or is Spatialite the best option?


Solution

  • You will have to figure out the best way to retrieve these positions from your database, but one way to add markers based on the map's camera's position is to add relevant markers in GoogleMap.OnCameraChangeListener.

    // Check to see if your GoogleMap variable exists.
    if (mGoogleMap != null) {
        // Respond to camera movements.
        mGoogleMap.setOnCameraMoveListener(new GoogleMap.OnCameraMoveListener() {
            @Override
            public void onCameraMove() {
                // Get the current bounds of the map's visible region.
                LatLngBounds bounds = mGoogleMap.getProjection().getVisibleRegion().latLngBounds;
                    // Loop through your list of positions.
                    for (LatLng latLng: yourLatLngList) {
                        // If a position is inside of the bounds,
                        if (bounds.contains(latLng)) {
                            // Add the marker.
                            mGoogleMap.addMarker(new MarkerOptions()
                                        .position(latLng));
                        }
                    }
            }
       });
    }
    

    I wouldn't suggest looping through a million positions every time the map's camera's position is changed. I think the best way for you to do it is to get the current bounds of the map's visible region when the camera is moved, then send the bounds in a call to your backend on a different thread, and have your backend do the work of finding the positions that fit in those bounds and then return that list back to your app where you can add markers accordingly.