18

I want to set the map zoom level to fit all markers on the map. I have used following method as said by many people, but it is not working for me. It is displaying some other point.

if (positions.size() > 0) {

    final LatLngBounds.Builder builder = new LatLngBounds.Builder();
    for (Marker m : positions) {
        builder.include(m.getPosition());
    }
    builder.include(positions.get(i).getPosition());
}

try {
    googleMap.setOnCameraChangeListener(new OnCameraChangeListener() {

        @Override
        public void onCameraChange(CameraPosition arg0) {

            googleMap.moveCamera(CameraUpdateFactory.newLatLngBounds(
                    builder.build(), UserDataManager.getInstance().getWidth(), 
                    UserDataManager.getInstance().getWidth(),0));
            googleMap.setOnCameraChangeListener(null);

        }
    });

} catch (IllegalStateException e) {
    // TODO: handle exception
    final View mapView = getSupportFragmentManager()
            .findFragmentById(R.id.map).getView();
    if (mapView.getViewTreeObserver().isAlive()) {
        mapView.getViewTreeObserver().addOnGlobalLayoutListener(
            new OnGlobalLayoutListener() {

                // We check which build version we are using.
                @Override
                public void onGlobalLayout() {
                    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
                        mapView.getViewTreeObserver()
                                .removeGlobalOnLayoutListener(
                                        this);
                    } else {
                        mapView.getViewTreeObserver()
                                .removeOnGlobalLayoutListener(
                                        this);
                    }

                    googleMap.setOnCameraChangeListener(new OnCameraChangeListener() {

                        @Override
                        public void onCameraChange(CameraPosition arg0) {

                            googleMap.moveCamera(CameraUpdateFactory.newLatLngBounds(
                                    builder.build(), 
                                    UserDataManager.getInstance().getWidth(), 
                                    UserDataManager.getInstance().getWidth(),0));
                            googleMap.setOnCameraChangeListener(null);

                        }
                    });

                }
            });
        }
    }
}
Sharmilee
  • 1,286
  • 1
  • 12
  • 20

4 Answers4

54

Try using this

//Calculate the markers to get their position
LatLngBounds.Builder b = new LatLngBounds.Builder();
for (Marker m : markers) {
    b.include(m.getPosition());
}
LatLngBounds bounds = b.build();
//Change the padding as per needed
CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds, 25,25,5);
mMap.animateCamera(cu);

Check this Google Maps v2 library that i have created that includes this functionality just use

Marker m1,m2, m3, m4 .... ;

mapHelper.zoomToFitMarkers(m1,m2, m3, m4 ....);

EDIT :

Get current location

LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
//You can use GPS_PROVIDER also
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, new LocationListener() {

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onProviderEnabled(String provider) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onProviderDisabled(String provider) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onLocationChanged(Location location) {
            // TODO Auto-generated method stub
            currentLatitude = location.getLatitude();
            currentLongitude = location.getLongitude();
            //Add your marker here and zoom to fit it
            //mapHelper.zoomToFitMarkers(m1,m2, m3, m4,mapHelper.addMarker(currentLatitude,currentLongitude,"Current Location"););
        }
    });
Girish Nair
  • 5,148
  • 5
  • 40
  • 61
  • i am getting same result :( – Sharmilee May 07 '13 at 11:47
  • This should work. Just don't hardcode 5 pixels and use density independent pixels instead. – MaciejGórski May 09 '13 at 10:53
  • 2
    using this code i get an error like "the size of the map should not be 0"... any idea ? – An-droid Jun 18 '13 at 14:54
  • 1
    @Yume117 : Use newLatLngBounds(bounds, 25,25,5); The 25,25 is the width and height, define your own width and height – Girish Nair Jun 19 '13 at 06:40
  • This worked for me..Is there a way to include current location here as well? I want to show my current location (Sri Lanka) and all markers (in Australia) in the map view. – TharakaNirmana Nov 21 '13 at 05:40
  • I have got the current location. I tried the github project of yours and it is working fine. I used this method: mapHelper.zoomToFitMarkers(m1,m2, m3, m4 ....); I have one more question, if my markers and the current location are in the same country, I want the map to zoom further. Is there a function for that? – TharakaNirmana Nov 21 '13 at 07:04
  • @TharakaNirmana: The `zoom()` method is responsible for zooming in `CameraPosition` class. So Change the zoomLevel variable in the project I have set it to 12, increase it for further zooming – Girish Nair Nov 21 '13 at 07:07
  • 5
    Use this `int width = getResources().getDisplayMetrics().widthPixels;` `newLatLngBounds(bounds, width, width, 25);` Getting screen width in pixels and making a rectangle(as per docs)/square of the side length equal to the screen width. Found 25 padding to be decent in my case. – Rahul Sainani Feb 28 '14 at 18:31
  • Is there a way to show entire world? I asked about it here: http://stackoverflow.com/q/42329186/878126 – android developer Feb 21 '17 at 10:27
  • @androiddeveloper : No you can't. I have been working with maps and tried a few things but its not close to what you need, An alternative would be drawing your own image to mimmic it – Girish Nair Feb 22 '17 at 18:28
  • @GirishNair Thing is I need to put views on top of it, as pins (with animation). Is it even possible on Google maps? – android developer Feb 22 '17 at 19:32
  • @androiddeveloper: Based on ola cabs 3d cars being presented on their app it seems to be a available but don't know more than that for it – Girish Nair Feb 23 '17 at 16:01
  • @GirishNair I see. Thanks. Made a request here: https://code.google.com/p/gmaps-api-issues/issues/detail?id=11510 . Please consider starring it. – android developer Feb 24 '17 at 00:15
  • @androiddeveloper: Sure – Girish Nair Feb 24 '17 at 11:28
4
mMap.moveCamera(CameraUpdateFactory.newLatLngBounds(builder.build(), 15));
Teraiya Mayur
  • 1,094
  • 10
  • 18
2

After many search I have found the most suitable answer:

//LatLngBound will cover all your marker on Google Maps
LatLngBounds.Builder builder = new LatLngBounds.Builder();
for (int i = 0; i < latLng.size(); i++) {
                        LatLng customMarkerLocation = new LatLng(latLng.get(i).getLat(), latLng.get(i).getLng());
                        mMap.addMarker(new MarkerOptions().position(customMarkerLocation).
                                icon(BitmapDescriptorFactory.fromBitmap(
                                        createCustomMarker(getActivity(), R.drawable.ic_pepsi, "Manish")))).setTitle("iPragmatech Solutions Pvt Lmt");

                        builder.include(customMarkerLocation); //include Point to be covered

                    }

                    LatLngBounds bounds = builder.build();
                    int width = getResources().getDisplayMetrics().widthPixels;
                    int height = getResources().getDisplayMetrics().heightPixels;
                    int padding = (int) (width * 0.15); // offset from edges of the map 15% of screen

                    // to animate camera with some padding and bound -cover- all markers
                    CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds, width, height, padding);
                    mMap.animateCamera(cu);

Reference: Adding custom image in Google Maps Marker, zoom in to keep all markers in the view

Mahmoud Zaher
  • 559
  • 6
  • 6
2

This is a solution in Kotlin

var listOfMarker = ArrayList<Marker>() // populate this elsewhere
val b = LatLngBounds.Builder()
for (m in listOfMarker) {
        b.include(m.position)
}
val bounds = b.build()
//Change the padding as per needed
val paddingFromEdgeAsPX = 100
var cu = CameraUpdateFactory.newLatLngBounds(bounds,paddingFromEdgeAsPX)
mMap.animateCamera(cu)