Hammad Nasir Hammad Nasir - 2 months ago 10
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.moveCamera(CameraUpdateFactory.newLatLng(mainUserLocation))
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

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() {

        mMap.clear();
        //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
        markersList.add(youMarker);
        markersList.add(playerMarker);


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

//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() {
            @Override
            public void onMapLoaded() {
                //animate camera here
                map.animateCamera(cu);

            }
        });


}

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

Hope this info helps.

Comments