【问题标题】:Adjusting google map (api v2) zoom level in android在android中调整谷歌地图(api v2)缩放级别
【发布时间】:2013-03-05 09:39:30
【问题描述】:

我在我的应用程序中使用maps api v2。我必须在地图上显示我的当前位置和目标位置,以便这两个位置在屏幕上都可见(以最大可能的缩放级别)。这是我迄今为止尝试过的......

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

    }

由于以下原因,应用程序被强制关闭: java.lang.IllegalStateException: Map 大小不应为 0。很可能,地图视图尚未出现 layout

如何获得最大可能的缩放级别?请帮帮我。

【问题讨论】:

    标签: android google-maps android-fragments


    【解决方案1】:

    在我的项目中,我使用com.google.android.gms.maps.model.LatLngBounds.Builder

    适应您的源代码后,它应该看起来像这样:

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

    【讨论】:

    • 谢谢。有用。使用 newLatLngBounds(LatLngBounds bounds, int width, int height, int padding)
    • 谢谢!只是一个小提示,答案中的 3 实际上是以 px 为单位的填充,所以你可能需要一个很大的数字。就我而言,我使用的是 250。
    【解决方案2】:

    避免此问题的一个好方法是对包含地图片段和侦听器的布局使用 ViewTreeObserver,以确保首先使用 addOnGlobalLayoutListener 初始化布局(并且没有宽度=0),如下所示:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-08
      • 1970-01-01
      • 2014-11-04
      • 2019-05-21
      相关资源
      最近更新 更多