java如何在谷歌地图上选择正确的缩放
我开发了一个应用程序,它使用带有多个标记的GMAP。用户可以添加或删除标记,但我的问题是选择良好的缩放级别以显示所有标记
如果用户添加或删除标记,缩放级别可能会改变
为了使摄像机居中,我使用以下代码:
double xMin = 90.0 ;
double xMax = 0.0 ;
double yMin = 90.0 ;
double yMax = 0.0 ;
LatLngBounds.Builder builder = new LatLngBounds.Builder();
for (Place place : places) {
if (place.getLatitude() < xMin)
xMin = place.getLatitude();
if (place.getLatitude() > xMax)
xMax = place.getLatitude();
if (place.getLongitude() < yMin)
yMin = place.getLongitude();
if (place.getLongitude() > yMax)
yMax = place.getLongitude();
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(new LatLng(place.getLatitude(), place.getLongitude()));
markerOptions.title(String.valueOf(place.getId()));
Marker marker = this.googleMap.addMarker(markerOptions);
allMarkersMap.put(marker, place);
displayMarkersMap.put(marker, place);
builder.include(marker.getPosition());
}
double xPos = (xMax + xMin) / 2;
double yPos = (yMax + yMin) / 2;
LatLngBounds bounds = builder.build();
int padding = 1; // offset from edges of the map in pixels
//CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngBounds(bounds, padding);
//this.googleMap.moveCamera(cameraUpdate);
LatLng latLng = new LatLng(xPos, yPos);
CameraPosition cameraPosition = new CameraPosition.Builder().target(latLng).zoom(2).build();
this.googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
但我找不到一个有好的缩放值的解决方案
# 1 楼答案
我知道您需要为地图定义一个中心,并确保所有标记都在视图中
在这种情况下,您可以计算包含标记的
LatLngBounds
,然后使用SphericalUtil.computeOffset
、SphericalUtil.computeDistanceBetween
和SphericalUtil.computeHeading
方法从Google Maps API Utility Library扩展它你可以测试这个方法