谷歌地图在经纬度边界内缩放

6

我有一张地图上有两个标记,它们应该同时显示。

这可以通过以下方法实现:

 final LatLngBounds.Builder builder = new LatLngBounds.Builder();
    for (Marker markerTemp : markers) {
        builder.include(markerTemp.getPosition());
    }

这个代码可以正常工作。但是,当标记点接近时,地图会非常缩小。

这是为什么:

  1. 我选择两个彼此相近的位置(缩放很好)
  2. 我选择两个距离较远的位置(缩放很好)
  3. 我选择两个彼此相近的位置(缩放保持不变,标记点重叠)

我已经查阅了很多相关链接,包括:

  1. https://stackoverflow.com/questions/34247347/initialize-google-map-to-zoom-to-bounds
  2. bounds google maps
  3. 在谷歌地图Android API V2中设置最大缩放级别
  4. Android map v2缩放以显示所有标记
  5. 在Android上调整Google地图(API V2)缩放级别
  6. 在LatLngBounds Builder上设置最大缩放级别
  7. Android缩放以适应Google地图V2上的所有标记

为什么不检查位置之间的距离,如果足够接近就放大地图呢? - Antonios Tsimourtos
如果您可以计算位置之间的距离,那么我可以基于此提供一个解决方案作为答案。 - Sreehari
@Stallion 我可以计算两个位置之间的距离。 - Miriana Itani
@NDorigatti 最终的 LatLngBounds.Builder 构建器 = new LatLngBounds.Builder(); 这段代码位于一个函数内部,该函数在每次标记更新时被调用。因此,构建器每次都会被重新创建。 - Miriana Itani
1
你需要遍历所有的标记点,对这个循环进行一些调试,并检查哪些标记点在列表中。可能你仍然有旧的标记点(比如法国)被重复添加进去了。 - N Dorigatti
显示剩余4条评论
3个回答

4

听起来你使用了一个函数来只在必要时缩小视野,但是没有使用函数将视野最大化。您能发布用于动画相机的部分吗?

如果您只使用

LatLngBounds bounds = builder.build();
map.animateCamera(CameraUpdateFactory.newLatLngBounds(bounds, 20));

它应该可以工作。确保调用它,不要将其包装在一个检查中,看看边界是否已经可见。


我正在做完全相同的事情。问题仍然存在。谢谢。 - Miriana Itani

2

不使用地图填充的完整解决方案。此函数将获取所有latlng对象,并返回一个Pair<LatLng,Integer>,其中第一个是pair.first将是中心,pair.second将是缩放级别。

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<LatLng, Integer> pair = getCenterWithZoomLevel(l1,l2,l3..);
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(pair.first, pair.second));

在代码片段中缺少distance()函数 - distance = distance(center, l[count]); - Pavlo28

2
您可以通过以下函数获取两个位置之间的距离,并根据此找到缩放级别。
计算两个位置之间直接距离的方法:
location1.distanceTo(location2);

现在需要计算半径,请使用以下公式。 dummy_radius 的值将是上面数值的一半。
double circleRad = dummy_radius*1000;//multiply by 1000 to make units in KM

private int getZoomLevel(double radius){
            double scale = radius / 500;
            return ((int) (16 - Math.log(scale) / Math.log(2)));
}

float zoomLevel = getZoomLevel(circleRad);
mGoogleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(LatLon, zoomLevel));

我现在会尝试一下。 - Miriana Itani

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接