Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adjusting google map (api v2) zoom level in android

I'am using maps api v2 in my app. I have to show my current location and target location on the map such that both the locations are visible (at the greatest possible zoom level) on the screen. Here is what i have tried so far...

googleMap = ((SupportMapFragment) getFragmentManager().findFragmentById(R.id.mapFragment)).getMap();

 if(googleMap != null){

        googleMap.setMyLocationEnabled(true);
        LatLng targetLocationLatLng = new LatLng(modelObject.getLattitude(), modelObject.getLongitude());
        LatLng currentLocationLatLng = new LatLng(this.currentLocationLattitude, this.currentLocationLongitude);
        googleMap.addMarker(new MarkerOptions().position(targetLocationLatLng).title(modelObject.getLocationName()).icon(BitmapDescriptorFactory.fromResource(R.drawable.location_icon)));
        LatLngBounds bounds = new LatLngBounds(currentLocationLatLng, targetLocationLatLng);
        googleMap.moveCamera(CameraUpdateFactory.newLatLngBounds(bounds, 3));

    }

App is force closing due to the following : java.lang.IllegalStateException: Map size should not be 0. Most likely, layout has not yet occured for the map view.

How can i get max possible zoom level? Please help me.

like image 679
Santhosh Avatar asked Nov 30 '25 11:11

Santhosh


2 Answers

In my project I use the com.google.android.gms.maps.model.LatLngBounds.Builder

Adapted to your source code it should look something like this:

Builder boundsBuilder = new LatLngBounds.Builder();
boundsBuilder.include(currentLocationLatLng);
boundsBuilder.include(targetLocationLatLng);
// pan to see all markers on map:
LatLngBounds bounds = boundsBuilder.build();
googleMap.moveCamera(CameraUpdateFactory.newLatLngBounds(bounds, 3));
like image 76
Matt Handy Avatar answered Dec 03 '25 00:12

Matt Handy


A good method to avoid this problem is to use a ViewTreeObserver to the layout containing the map fragment and a listener, to ensure that the layout has first been initialised (and hasn't a width=0) using addOnGlobalLayoutListener, as below:

  private void zoomMapToLatLngBounds(final LinearLayout layout,final GoogleMap mMap, final LatLngBounds bounds){

    ViewTreeObserver vto = layout.getViewTreeObserver(); 
    vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() { 
        @SuppressWarnings("deprecation")
        @Override 
        public void onGlobalLayout() { 
          layout.getViewTreeObserver().removeGlobalOnLayoutListener(this); 
          mMap.moveCamera(CameraUpdateFactory.newLatLngBounds(bounds,OVERVIEW_MAP_PADDING));
        } 
    });

}
like image 29
Paul Crease Avatar answered Dec 03 '25 01:12

Paul Crease



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!