如何在同一活动中获得两个MapFragments - Google Map Api

时间:2017-04-18 16:53:26

标签: android google-maps mapfragment

我需要在活动中显示两个具有两个不同位置的MapFragments。 在我的XML文件中,我有两个名为“map”和“map_two”的MapFragments,而在java中,我在onCreate中的代码是:

com.google.android.gms.maps.MapFragment mapFragment = (MapFragment) getFragmentManager().findFragmentById(map);
        mapCount = 1;
        mapFragment.getMapAsync(this);
        com.google.android.gms.maps.MapFragment mapFragmentTwo = (MapFragment) getFragmentManager().findFragmentById(map_two);
        mapCount = 2;
        mapFragmentTwo.getMapAsync(this);

然后我重写onMapReady:

@Override
public void onMapReady(GoogleMap googleMap) {
    if (mapCount == 1){
    mMap = googleMap;
    LatLng vannes = new LatLng(47.66, -2.75);
    mMap.addMarker(new MarkerOptions().position(vannes).title("Vannes"));
    mMap.moveCamera(CameraUpdateFactory.newLatLng(vannes));

    } else if (mapCount == 2){
        mMap = googleMap;
        LatLng bordeaux = new LatLng(44.833328, -0.56667);
        mMap.addMarker(new MarkerOptions().position(bordeaux).title("Bordeaux"));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(bordeaux));

    } 
}

我的问题是两张地图显示的位置相同,而我想显示两个不同的位置。你知道怎么做吗?

谢谢,

亚历

1 个答案:

答案 0 :(得分:4)

最好的方法是为每张地图创建2个不同的回调:

public OnMapReadyCallback onMapReadyCallback1(){
        return new OnMapReadyCallback() {
            @Override
            public void onMapReady(GoogleMap googleMap) {
                mMap = googleMap;
                LatLng vannes = new LatLng(47.66, -2.75);
                mMap.addMarker(new MarkerOptions().position(vannes).title("Vannes"));
                mMap.moveCamera(CameraUpdateFactory.newLatLng(vannes));
            }
        };
    }

    public OnMapReadyCallback onMapReadyCallback2(){
        return new OnMapReadyCallback() {
            @Override
            public void onMapReady(GoogleMap googleMap) {
                mMap = googleMap;
                LatLng bordeaux = new LatLng(44.833328, -0.56667);
                mMap.addMarker(new MarkerOptions().position(bordeaux).title("Bordeaux"));
                mMap.moveCamera(CameraUpdateFactory.newLatLng(bordeaux));

            }
        };
    }

Activity中添加这两种方法后,您必须在地图中设置它们:

com.google.android.gms.maps.MapFragment mapFragment = (MapFragment) getFragmentManager().findFragmentById(map);
        mapCount = 1;
        mapFragment.getMapAsync(onMapReadyCallback1());
        com.google.android.gms.maps.MapFragment mapFragmentTwo = (MapFragment) getFragmentManager().findFragmentById(map_two);
        mapCount = 2;
        mapFragmentTwo.getMapAsync(onMapReadyCallback2());