2

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.

moDev
  • 5,248
  • 4
  • 33
  • 63
Santhosh
  • 4,956
  • 12
  • 62
  • 90

2 Answers2

19

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));
Matt Handy
  • 29,855
  • 2
  • 89
  • 112
  • Thanks. It works. using newLatLngBounds(LatLngBounds bounds, int width, int height, int padding) – Santhosh Mar 05 '13 at 14:50
  • Thanks! Just a small note, the 3 of the answer is actually the padding in px, so you'll probably need a big number. In my case I'm using 250. – Teo Inke Jun 26 '15 at 16:54
1

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));
        } 
    });

}
Paul Crease
  • 150
  • 5