Google 地图 Android LatLngBounds

Google Maps Android LatLngBounds

添加标记后,我使用以下代码缩放到地图上的最大缩放级别。它可以工作,但前提是我在 500 毫秒的延迟可运行范围内拥有它。如果它取出来,它不起作用。我知道我错过了一些明显的东西,但我不知道我错过了什么。谁能告诉我需要将 LatLngBounds 代码放在哪里才能在没有 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);

您可能需要等待地图加载回调才能缩放:

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

您需要立即显示地图:

mMapView.onResume();
    @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));
            }
        });
    }