Hammad Nasir Hammad Nasir - 10 months ago 44
Java Question

I have 2 marker on my map. How to focus camera on both and not just move camera to one of them?

I have implemented Google Maps in my app and have added 2 markers on it.

Here's how:

LatLng mainUserLocation = new LatLng(Double.valueOf(currentLt), Double.valueOf(currentLn));
mMap.addMarker(new MarkerOptions().position(mainUserLocation).title("You"));
mMap.animateCamera(CameraUpdateFactory.zoomTo(20), 2000, null);

LatLng otherPlayersLocation = new LatLng(currentLtAU, currentLnAU);
mMap.addMarker(new MarkerOptions().position(otherPlayersLocation).title(nameAU));

The problem is that the camera is zooming and getting focused on one marker and the other marker is getting out of sight!

I want both of the markers or all the markers to remain in sight. How to achieve this?

Please let me know.

Answer Source

So this question has already been answered here and not mentioning it would be violation of good community ethics.

Still, here I will try to break it down in your context. So that you understand better what steps you need to take.

LatLng mainUserLocation = new LatLng(Double.valueOf(currentLt), Double.valueOf(currentLn));

LatLng otherPlayersLocation = new LatLng(currentLtAU, currentLnAU);

    public void showMap() {

        //Create your Markers List
        List<Marker> markersList = new ArrayList<Marker>();
        Marker youMarker = mMap.addMarker(new MarkerOptions().position(mainUserLocation).title("You"));
        Marker playerMarker = mMap.addMarker(new MarkerOptions().position(otherPlayersLocation).title(nameAU));

        //Add them to your list

//get the latLngbuilder from the marker list
        builder = new LatLngBounds.Builder();
        for (Marker m : markersList) {

//Bounds padding here
        int padding = 50;

        //Create bounds here
        LatLngBounds bounds = builder.build();

//Create camera with bounds
        cu = CameraUpdateFactory.newLatLngBounds(bounds, padding);

//Check map is loaded
        map.setOnMapLoadedCallback(new GoogleMap.OnMapLoadedCallback() {
            public void onMapLoaded() {
                //animate camera here



So in your code you need to setup a method like this and just call showMap().

Hope this info helps.