使用Google Maps Android API v2,我尝试使用LatLngBounds.Builder()
使用数据库中的点设置地图的边界。我认为我很接近,但活动正在崩溃,因为我认为我没有正确加载积分。我可能只是几行之外。
//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));
}
}
我认为在安排for循环以获取所有汽车时可能会出现错误,如果我删除了边界语句,地图点就像我预期的那样正确绘制,但没有正确地限制地图。
答案 0 :(得分:28)
你每次都在循环中创建一个新的LatLngBounds.Builder()。 试试这个
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));
}