Android googlemaps v2 finish loading event or call

2019-05-24 13:22发布

问题:

I want to do something after the google maps has loaded(maptiles have been filled) is there anyway to achieve that?

回答1:

As noted by qubz, the ViewTreeObserver can be used to achieve a callback after the loading of the map has completed, so the user will get e.g. the correct location right after start-up:

@Override
public void onCreate(Bundle savedInstanceState) {
    // This is a small hack to enable a onMapLoadingCompleted-functionality to the user.
    final View mapView = getSupportFragmentManager().findFragmentById(R.id.google_map_fragment).getView();
    if (mapView.getViewTreeObserver().isAlive()) {
        mapView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
            @SuppressWarnings("deprecation")
            // We use the new method when supported
            @SuppressLint("NewApi")
            // 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);
                }
                // Send notification that map-loading has completed.
                onMapFinishedLoading();
            }
        });
    }
}

protected void onMapFinishedLoading() {
    // Do whatever you want to do. Map has completed loading at this point.
    Log.i(TAG, "Map finished loading.");
    GoogleMap mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.google_map_fragment))
                    .getMap();
    mMap.moveCamera(CameraUpdateFactory.zoomIn());
}