简体   繁体   中英

Add multiple markers to the google map and zoom to include all of them

I am using the following code to add markers to google map and create bounds.
What I am trying to do is add the markers and zoom in a way that all of them are visible in a map that has fixed height

LatLngBounds.Builder builder = new LatLngBounds.Builder();  
for(Location loc: locations) {  
  MarkerOptions marker = new MarkerOptions().position(loc.lat, loc.lon);  
  googleMap.addMarker(marker);  
  builder.include(marker.getPosition());  
}    

LatLngBounds bounds = builder.build();  
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngBounds(bounds, 5);  
googleMap.animateCamera(cameraUpdate);  

Whether all icons will appear or not depends on the value I add for padding.
If I increase the value all show up. Otherwise others are hidden.
How do I come up with the correct value for the padding taking into account that my googleMap has a fixed set width?

Try set a center of the position where you want initiate the map (set a coor with latitude and longitude of any of your markers) and set a level of zoom:

LatLng center = centro = new LatLng(lat, long);

CameraPosition cameraPosition = new CameraPosition.Builder().target(center).zoom(17).bearing(0).tilt(0).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));

First of all your code is correct and it may depend on your specifics on how to show your markers on the map. If you will look on this sample code, the developer provided a different value for padding.

/*initialize the padding for map boundary/
int padding = 50;
/*create the bounds from latlngBuilder to set into map camera/
LatLngBounds bounds = builder.build();
/*create the camera with bounds and padding to set into map/
cu = CameraUpdateFactory.newLatLngBounds(bounds, padding);
/*call the map call back to know map is loaded or not/
map.setOnMapLoadedCallback(new GoogleMap.OnMapLoadedCallback() {
@Override
public void onMapLoaded() {
/*set animated zoom camera into map/
map.animateCamera(cu);

}
});
}

Here are some links that provides solution and own implementation using newLatLngBounds :

Hope it helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM