一般我們可以手動設(shè)置地圖縮放級別谢揪,但有時候需求會要求根據(jù)地圖上的Marker,自定義縮放級別,這個時候就用到下面的代碼:
LatLngBounds.Builder boundsBuilder = new LatLngBounds.Builder();//存放所有點的經(jīng)緯度
for(int i=0;i<markers.size();i++){
boundsBuilder.include(markers.get(i).getPosition());//把所有點都include進(jìn)去(LatLng類型)
}
aMap.animateCamera(CameraUpdateFactory.newLatLngBounds(boundsBuilder.build(), 15));//第二個參數(shù)為四周留空寬度
animateCamera也可以使用moveCamera方法谢澈,效果一樣,15有點小可以設(shè)置200御板,試試效果吧锥忿。
這個樣有個問題,就是屏幕中心點和當(dāng)前坐標(biāo)點不重合了怠肋,高德官方給出了方法如下:
/**
* 縮放移動地圖敬鬓,保證所有自定義marker在可視范圍中,且地圖中心點不變笙各。
*/
public void zoomToSpanWithCenter() {
if (pointList != null && pointList.size() > 0) {
if (aMap == null)
return;
centerMarker.setVisible(true);
centerMarker.showInfoWindow();
LatLngBounds bounds = getLatLngBounds(centerPoint, pointList);
aMap.moveCamera(CameraUpdateFactory.newLatLngBounds(bounds, 50));
}
}
//根據(jù)中心點和自定義內(nèi)容獲取縮放bounds
private LatLngBounds getLatLngBounds(LatLng centerpoint, List<LatLng> pointList) {
LatLngBounds.Builder b = LatLngBounds.builder();
if (centerpoint != null){
for (int i = 0; i < pointList.size(); i++) {
LatLng p = pointList.get(i);
LatLng p1 = new LatLng((centerpoint.latitude * 2) - p.latitude, (centerpoint.longitude * 2) - p.longitude);
b.include(p);
b.include(p1);
}
}
return b.build();
}
/**
* 縮放移動地圖钉答,保證所有自定義marker在可視范圍中。
*/
public void zoomToSpan() {
if (pointList != null && pointList.size() > 0) {
if (aMap == null)
return;
centerMarker.setVisible(false);
LatLngBounds bounds = getLatLngBounds(pointList);
aMap.moveCamera(CameraUpdateFactory.newLatLngBounds(bounds, 50));
}
}
/**
* 根據(jù)自定義內(nèi)容獲取縮放bounds
*/
private LatLngBounds getLatLngBounds( List<LatLng> pointList) {
LatLngBounds.Builder b = LatLngBounds.builder();
for (int i = 0; i < pointList.size(); i++) {
LatLng p = pointList.get(i);
b.include(p);
}
return b.build();
}
關(guān)鍵方法: LatLng p1 = new LatLng((centerpoint.latitude * 2) - p.latitude, (centerpoint.longitude * 2) - p.longitude);
詳情見高德官方鏈接:https://lbs.amap.com/dev/demo/map-zoomtospan#Android