animateCamera works and moveCamera doesn't for GoogleMap - Android

后端 未结 4 1501
感情败类
感情败类 2021-01-14 16:36

I need to move Camera to cover all Markers on it. So, I build LatLngBounds and then try to call mMap.moveCamera(CameraUpdateFactory.newLatLngBounds(latLng

4条回答
  •  孤独总比滥情好
    2021-01-14 16:54

    As clearly documented here OnMapReadyCallback

    Note that OnMapReadyCallback does not guarantee that the map has undergone layout. Therefore, the map's size may not have been determined by the time the callback method is called. If you need to know the dimensions or call a method in the API that needs to know the dimensions, get the map's View and register an ViewTreeObserver.OnGlobalLayoutListener as well.

    Do not chain the OnMapReadyCallback and OnGlobalLayoutListener listeners, but instead register and wait for both callbacks independently, since the callbacks can be fired in any order.

    So you have to use both (onMapReady,onGlobalLayout) callbacks to make sure that map have been fully loaded and size has been determined.

    private GoogleMap mMap;
    private boolean isMapLoaded;
    
    SupportMapFragment mapFragment = (SupportMapFragment)getSupportFragmentManager()
                .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);
    mapFragment.getView().getViewTreeObserver().addOnGlobalLayoutListener(this);
    
    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        if (!isMapLoaded) {
            isMapLoaded = true;
            return;
        }
        initMap();
    }
    
    @Override
    public void onGlobalLayout() {
        if (!isMapLoaded) {
            isMapLoaded = true;
            return;
        }
        initMap();
    }
    
    private void initMap() {
       //maps fully loaded instance with defined size will be available here.
       //mMap.animateCamera();
       //mMap.moveCamera();
    }
    

提交回复
热议问题