Phil
Phil

Reputation: 4069

Google Maps Android LatLngBounds

I'm using the following code to zoom to the maximum zoom level on my map after I add my markers. It works, but only if I have it inside of the 500 miliseconds delay runnable. If it take it out, it does not work. I know I'm missing something obvious, but I don't know what i was missed. Can anyone tell me where I need to place this the LatLngBounds code to have it work without the Runnable?

// Expand our Zoom to fit all markers
        LatLngBounds.Builder builder = new LatLngBounds.Builder();

        //the include method will calculate the min and max bound.
        builder.include(myLocationPin.getPosition());
        builder.include(placeLocationPin.getPosition());

        final LatLngBounds bounds = builder.build();

        final int zoomWidth = getResources().getDisplayMetrics().widthPixels;
        final int zoomHeight = getResources().getDisplayMetrics().heightPixels;
        final int zoomPadding = (int) (zoomWidth * 0.10); // offset from edges of the map 12% of screen

        final Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                map.animateCamera(CameraUpdateFactory.newLatLngBounds(bounds,zoomWidth,zoomHeight,zoomPadding));
            }
        }, 500);

Upvotes: 2

Views: 6849

Answers (3)

kgsharathkumar
kgsharathkumar

Reputation: 1399

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_view_map);

        map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
                .getMap();

        map.setOnMapLoadedCallback(new GoogleMap.OnMapLoadedCallback() {
            @Override
            public void onMapLoaded() {
                map.addMarker(new MarkerOptions().title("your title")
                        .snippet("your desc")
                        .position(new LatLng(-22.2323,-2.32323)));
                map.animateCamera(CameraUpdateFactory.newLatLngBounds(bounds,zoomWidth,
                                                                zoomHeight,zoomPadding));
            }
        });
    }

Upvotes: 3

oskarko
oskarko

Reputation: 4198

You need to get the map to display immediately:

mMapView.onResume();

Upvotes: -1

Michael A
Michael A

Reputation: 5850

You probably need to wait for the map loaded callback before you can zoom it:

@Override
public void onMapLoaded() {
if (mMap != null) {
 map.animateCamera(CameraUpdateFactory.newLatLngBounds(bounds,zoomWidth,zoomHeight,zoomPadding)); }}

Upvotes: 2

Related Questions