6

使用 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 循环以获取所有汽车可能存在错误,如果我删除边界语句,则地图点按预期正确绘制但未正确界定地图。

4

1 回答 1

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));
}
于 2013-02-02T04:28:20.423 回答