220

我在GoogleMap中有10个标记。我想尽可能放大并保留所有标记?在早期版本中,这可以从zoomToSpan()实现,但在V2中,我不知道如何做到这一点。此外,我知道需要可见的圆的半径。Android地图v2放大以显示所有标记

+1

我的答案会给你一个最新的Android API最简单的解决方案。 http://stackoverflow.com/a/38013331/1348522 – 2016-11-08 10:12:47

回答

660

您应该使用CameraUpdate类(可能)执行所有程序化的地图移动。

要做到这一点,首先计算所有标记的范围,像这样:CameraUpdateFactory

int padding = 0; // offset from edges of the map in pixels 
CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds, padding); 

最后移动地图

LatLngBounds.Builder builder = new LatLngBounds.Builder(); 
for (Marker marker : markers) { 
    builder.include(marker.getPosition()); 
} 
LatLngBounds bounds = builder.build(); 

通过使用工厂然后得到一个运动的描述对象:

googleMap.moveCamera(cu); 

或者如果你想动画:

googleMap.animateCamera(cu); 

这是所有:)

澄清1

几乎所有的运动方法要求已通过布局过程中Map对象。您可以使用addOnGlobalLayoutListener构造等待发生这种情况。详细信息可以在评论中找到这个答案和其余的答案。您还可以找到一个complete code for setting map extent using addOnGlobalLayoutListener here

澄清2

一种意见指出,使用这种方法只有一个标记导致地图缩放设置为一个“奇怪的”缩放级别(这我认为是可用于指定位置的最大缩放级别)。我认为这是预料之中,因为:

  1. LatLngBounds bounds实例将有northeast属性等于southwest,这意味着本bounds覆盖地球面积的部分正好是零。 (这是合乎逻辑的,因为单个标记没有区域。)
  2. 通过将bounds传递给CameraUpdateFactory.newLatLngBounds您基本上要求计算这样一个缩放级别,即bounds(具有零区域)将覆盖整个地图视图。
  3. 您实际上可以在一张纸上执行此计算。作为答案的理论缩放级别是+ ∞(正无穷大)。在实践中,Map对象不支持该值,因此它被限制为给定位置允许的更合理的最大级别。

另一种方式把它:Map对象怎么能知道什么缩放级别应该是选择一个单一位置?也许最佳值应该是20(如果它代表特定的地址)。或者也许11(如果它代表一个城镇)。或者,也许6(如果它代表一个国家)。 API不是那么聪明,这个决定取决于你。

所以,你应该简单地检查是否markers只有一个位置,如果是这样,使用一个:

  • CameraUpdate cu = CameraUpdateFactory.newLatLng(marker.getPosition()) - 去标记的位置,离开当前缩放级别不变。
  • CameraUpdate cu = CameraUpdateFactory.newLatLngZoom(marker.getPosition(), 12F) - 去标记的位置,设置缩放级别任意选择值12
+19

应该指出的是,移动不能从onCreate调用发生,视图必须被创建。我需要使用addOnGlobalLayoutListener来获取适当的样本。 – 2013-08-01 17:57:42

+6

@巴尔,这部分是真的。准确地说:*一些*移动方法在创建地图对象后不会正常工作。其原因是地图对象尚未被测量*但尚未经过布局处理。一个典型的解决方法是使用'addOnGlobalLayoutListener()'或'post()'和适当的'Runnable'。这正是获取标记屏幕坐标不能在'onCreate'中完成的原因 - 请参阅http://stackoverflow.com/q/14429877/1820695但是,您甚至可以在布局发生之前使用某些方法 - 例如。 'CameraUpdateFactory.newLatLngBounds()'带有* 4个参数*。 – andr 2013-08-01 19:18:04

+1

男人,你救了我一天...实际上是试图自己做,手动计算边界,并缩放标记是在它...工作相当丑陋,但用你的简单方法,它的作品像一个魅力。谢谢 – Bibu 2014-03-08 20:40:40

11

所以

I needed to use addOnGlobalLayoutListener to get the appropriate sample

例如,您的谷歌地图里面的RelativeLayout:

RelativeLayout mapLayout = (RelativeLayout)findViewById(R.id.map_layout); 
mapLayout.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() { 
     @Override 
     public void onGlobalLayout() { 
      //and write code, which you can see in answer above 
     } 
    }); 
11

我无法使用onGlobalLayoutlistener,所以这里有另一个解决方案来防止 "Map size can't be 0. Most likely, layout has not yet occured for the map view. Either wait until layout has occurred or use newLatLngBounds(LatLngBounds, int, int, int) which allows you to specify the map's dimensions."错误:

mMap.setOnMapLoadedCallback(new GoogleMap.OnMapLoadedCallback() { 
@Override 
public void onMapLoaded() { 
    mMap.moveCamera(CameraUpdateFactory.newLatLngBounds(builder.build(), 15)); 
} 
}); 
+0

这一个比OnGlobalLayoutListener更长的路,所以对我来说它仍然显示首先映射默认区域/缩放,然后将摄像机移动到我需要的地方 – Till 2016-07-05 12:47:16

0

使用“getCenterCoordinate”方法获取中心坐标并在CameraPosition中使用。

private void setUpMap() { 
    mMap.setMyLocationEnabled(true); 
    mMap.getUiSettings().setScrollGesturesEnabled(true); 
    mMap.getUiSettings().setTiltGesturesEnabled(true); 
    mMap.getUiSettings().setRotateGesturesEnabled(true); 

    clientMarker = mMap.addMarker(new MarkerOptions() 
      .position(new LatLng(Double.valueOf(-12.1024174), Double.valueOf(-77.0262274))) 
      .icon(BitmapDescriptorFactory.fromResource(R.mipmap.ic_taxi)) 
    ); 
    clientMarker = mMap.addMarker(new MarkerOptions() 
      .position(new LatLng(Double.valueOf(-12.1024637), Double.valueOf(-77.0242617))) 
      .icon(BitmapDescriptorFactory.fromResource(R.mipmap.ic_location)) 
    ); 

    camPos = new CameraPosition.Builder() 
      .target(getCenterCoordinate()) 
      .zoom(17) 
      .build(); 
    camUpd3 = CameraUpdateFactory.newCameraPosition(camPos); 
    mMap.animateCamera(camUpd3); 
} 


public LatLng getCenterCoordinate(){ 
    LatLngBounds.Builder builder = new LatLngBounds.Builder(); 
    builder.include(new LatLng(Double.valueOf(-12.1024174), Double.valueOf(-77.0262274))); 
    builder.include(new LatLng(Double.valueOf(-12.1024637), Double.valueOf(-77.0242617))); 
    LatLngBounds bounds = builder.build(); 
    return bounds.getCenter(); 
} 
-2
//For adding a marker in Google map 
     MarkerOptions mp = new MarkerOptions(); 
     mp.position(new LatLng(Double.parseDouble(latitude), Double.parseDouble(longitude))); 
     mp.snippet(strAddress); 
     map.addMarker(mp); 

     try { 

      b = new LatLngBounds.Builder(); 

      if (MapDetailsList.list != null && MapDetailsList.list.size() > 0) { 

       for (int i = 0; i < MapDetailsList.list.size(); i++) { 

        b.include(new LatLng(Double.parseDouble(MapDetailsList.list.get(i).getLatitude()), 
          Double.parseDouble(MapDetailsList.list.get(i).getLongitude()))); 

       } 
       LatLngBounds bounds = b.build(); 

       DisplayMetrics displayMetrics = getResources().getDisplayMetrics(); 
       int width = displayMetrics.widthPixels; 
       int height = displayMetrics.heightPixels; 

       // Change the padding as per needed 
       CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds, width-200, height-200, 5); 
       // map.setCenter(bounds.getCenter()); 

       map.animateCamera(cu); 

      } 

     } catch (Exception e) { 

     } 

http://i64.tinypic.com/2qjybh4.png

http://i63.tinypic.com/flzwus.png

http://i63.tinypic.com/112g5fm.png

2

注意 - 这不是原来的问题的解决方案。这是对above讨论的子问题之一的解决方案。

解决@andr 澄清2 -

它真的有问题时,有只有一个边界标记,由于它的缩放级别设置为一个非常高的水平(级21)。而Google目前没有提供任何设置最大缩放级别的方法。这也可能发生在有多于一个标记但它们彼此非常接近时。然后也会发生同样的问题。

解决方案 - 假设您希望您的地图不超过16个缩放级别。然后,后做事 -

CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds, padding); 
mMap.moveCamera(cu); 

检查您的缩放级别已越过16级(或任何你想要的) -

float currentZoom = mMap.getCameraPosition().zoom; 

如果这个级别大于16,这也只会是如果有是非常少的标记或所有标记都非常接近对方,后来干脆只塞汀缩放比例为16

mMap.moveCamera(CameraUpdateFactory.zoomTo(16)); 

这样,你永远不会有在p缩小你在那个特定的位置地图@andr也很好地解释了“奇异”缩放级别的问题。

+0

很好的解决方案,但是如果您将“cu”对象置于MapReady()内部,那么在这种情况下会出现一个错误行为:**收到位置 - >缩放很大,它16 - >然后用户放大 - >位置再次收到和相机被放回到级别16 **。 当几乎实时收到位置时,这可能会成为问题,因为它会一直返回到第16级。 – 2017-02-01 09:32:04

+0

“Google现在不提供任何方法来设置最大缩放级别。” - 不正确:https ://developers.google.com/android/reference/com/google/android/gms/maps/GoogleMap.html#setMaxZoomPreference(float) – user1209216 2017-05-22 07:01:59

1

这会帮助..从谷歌apis演示

private List<Marker> markerList = new ArrayList<>(); 
Marker marker = mGoogleMap.addMarker(new MarkerOptions().position(geoLatLng) 
       .title(title)); 
markerList.add(marker); 
    // Pan to see all markers in view. 
    // Cannot zoom to bounds until the map has a size. 
    final View mapView = getSupportFragmentManager().findFragmentById(R.id.map).getView(); 
    if (mapView!=null) { 
     if (mapView.getViewTreeObserver().isAlive()) { 
      mapView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { 
       @SuppressWarnings("deprecation") // We use the new method when supported 
       @SuppressLint("NewApi") // We check which build version we are using. 
       @Override 
       public void onGlobalLayout() { 
        //Calculate the markers to get their position 
        LatLngBounds.Builder b = new LatLngBounds.Builder(); 
        for (Marker m : markerList) { 
         b.include(m.getPosition()); 
        } 
        // also include current location to include in the view 
        b.include(new LatLng(mLocation.getLatitude(),mLocation.getLongitude())); 

        LatLngBounds bounds = b.build(); 
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) { 
         mapView.getViewTreeObserver().removeGlobalOnLayoutListener(this); 
        } else { 
         mapView.getViewTreeObserver().removeOnGlobalLayoutListener(this); 
        } 
        mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngBounds(bounds, 50)); 
       } 
      }); 
     } 
    } 

清除信息看看这个网址。 https://github.com/googlemaps/android-samples/blob/master/ApiDemos/app/src/main/java/com/example/mapdemo/MarkerDemoActivity.java

52

谷歌地图V2:为Android棉花糖6(API 23,API 24,API 25),以及边界最佳的工作解决方案中放大的MarkerOptions,工程在Xamarin还

LatLngBounds.Builder builder = new LatLngBounds.Builder(); 

//the include method will calculate the min and max bound. 
builder.include(marker1.getPosition()); 
builder.include(marker2.getPosition()); 
builder.include(marker3.getPosition()); 
builder.include(marker4.getPosition()); 

LatLngBounds bounds = builder.build(); 

int width = getResources().getDisplayMetrics().widthPixels; 
int height = getResources().getDisplayMetrics().heightPixels; 
int padding = (int) (width * 0.10); // offset from edges of the map 10% of screen 

CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds, width, height, padding); 

mMap.animateCamera(cu); 
+0

谢谢你:) – 2016-10-30 09:58:41

+1

为了更好看的填充,使用高度而不是宽度和采取20%,而不是10%。 – noob 2017-07-31 08:50:44

+0

不错,这也适用于Xamarin! – JMK 2017-09-02 13:39:33

3

Working fine for me.

从这个代码,我在地图屏幕上显示特定缩放的多个标记。

//声明的变量

private LatLngBounds bounds; 
private LatLngBounds.Builder builder; 

//方法与绘制图标添加多个标记点

private void drawMarker(LatLng point, String text) { 

     MarkerOptions markerOptions = new MarkerOptions(); 
     markerOptions.position(point).title(text).icon(BitmapDescriptorFactory.fromResource(R.drawable.icon)); 
     mMap.addMarker(markerOptions); 
     builder.include(markerOptions.getPosition()); 

    } 

//对于添加多个标记可见在地图上

@Override 
    public void onMapReady(GoogleMap googleMap) { 
     mMap = googleMap; 
     builder = new LatLngBounds.Builder(); 
    for (int i = 0; i < locationList.size(); i++) { 

     drawMarker(new LatLng(Double.parseDouble(locationList.get(i).getLatitude()), Double.parseDouble(locationList.get(i).getLongitude())), locationList.get(i).getNo()); 

    } 
    bounds = builder.build(); 
    CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds, 0); 
    mMap.animateCamera(cu); 
0

我有类似的问题,使用下面的代码解决了问题:

CameraUpdateFactory.newLatLngBounds(bounds, 200, 200, 5)我的情况一般位置差异不超过两个邻居城市。

zoom to fit all markers on map google maps v2

0

我有一个其他的方式做同样的事情完美的作品。所以后面的想法显示屏幕上的所有标记,我们需要一个中心拉长和缩放级别。这里有一个函数可以让你和所有标记的Latlng对象作为输入。

public Pair<LatLng, Integer> getCenterWithZoomLevel(LatLng... l) { 
    float max = 0; 

    if (l == null || l.length == 0) { 
     return null; 
    } 
    LatLngBounds.Builder b = new LatLngBounds.Builder(); 
    for (int count = 0; count < l.length; count++) { 
     if (l[count] == null) { 
      continue; 
     } 
     b.include(l[count]); 
    } 

    LatLng center = b.build().getCenter(); 

    float distance = 0; 
    for (int count = 0; count < l.length; count++) { 
     if (l[count] == null) { 
      continue; 
     } 
     distance = distance(center, l[count]); 
     if (distance > max) { 
      max = distance; 
     } 
    } 

    double scale = max/1000; 
    int zoom = ((int) (16 - Math.log(scale)/Math.log(2))); 
    return new Pair<LatLng, Integer>(center, zoom); 
} 

该函数返回对对象,您可以像使用

Pair pair = getCenterWithZoomLevel(l1,l2,l3..); mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(pair.first, pair.second));

可以代替使用填充您的标记从屏幕边界保持距离,你可以通过调整-1变焦。

相关问题