Using Google Maps Android API v2, I am trying to set the bounds of the map using LatLngBounds.Builder()
with points from a database. I think I am close, however the activity is crashing because I don't think I am properly loading the points. I may be just a couple of lines away.
//setup map
private void setUpMap() {
//get all cars from the datbase with getter method
List<Car> K = db.getAllCars();
//loop through cars in the database
for (Car cn : K) {
//add a map marker for each car, with description as the title using getter methods
mapView.addMarker(new MarkerOptions().position(new LatLng(cn.getLatitude(), cn.getLongitude())).title(cn.getDescription()));
//use .include to put add each point to be included in the bounds
bounds = new LatLngBounds.Builder().include(new LatLng(cn.getLatitude(), cn.getLongitude())).build();
//set bounds with all the map points
mapView.moveCamera(CameraUpdateFactory.newLatLngBounds(bounds, 50));
}
}
I think there may be an error in how I arranged the for loop to get all the cars, if I remove the bounds statements the map point are plotted correctly as I expected but not bounding the map properly.
you are creating a new LatLngBounds.Builder() everytime in the loop. try this
private LatLngBounds.Builder bounds;
//setup map
private void setUpMap() {
bounds = new LatLngBounds.Builder();
//get all cars from the datbase with getter method
List<Car> K = db.getAllCars();
//loop through cars in the database
for (Car cn : K) {
//add a map marker for each car, with description as the title using getter methods
mapView.addMarker(new MarkerOptions().position(new LatLng(cn.getLatitude(), cn.getLongitude())).title(cn.getDescription()));
//use .include to put add each point to be included in the bounds
bounds.include(new LatLng(cn.getLatitude(), cn.getLongitude()));
}
//set bounds with all the map points
mapView.moveCamera(CameraUpdateFactory.newLatLngBounds(bounds.build(), 50));
}