2

in my following code, getMap() returns null, which stop the app. If I don't do anything with the map (i.e, removing the last two lines), it shows correctly. Any idea why? Thanks.

public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        FragmentManager fragmentManager = getSupportFragmentManager();
        SupportMapFragment mapFragment = SupportMapFragment.newInstance();
        mapFragmentId = mapFragment.getId();
        FragmentTransaction transaction =  fragmentManager.beginTransaction();
        transaction.add(R.id.my_container, mapFragment);
        transaction.commit();

        mMap = mapFragment.getMap();
        mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
    }
4

2 回答 2

3

重复:SupportMapFragment.getmap() 返回 null

检查您的布局 xml 文件。我注意到我没有引用: android:name="com.google.android.gms.maps.SupportMapFragment" 而是: android:name="com.google.android.gms.maps.MapFragment"

名称应为:android:name="com.google.android.gms.maps.SupportMapFragment"

于 2014-12-04T08:51:18.097 回答
2

如果getMap()返回 null 那是因为 Map 尚未准备好或GooglePlayServices已过时。你最好使用类似的东西:

int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
        if(resultCode != ConnectionResult.SUCCESS)
        {
            Builder builder = new AlertDialog.Builder(Main.this);
            builder.setMessage(getResources().getString(R.string.error_getting_maps));
            builder.setCancelable(true);
            builder.setPositiveButton("OK", null);
            AlertDialog dialog = builder.create();
            dialog.show();
        } else {
            _map = ((SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
            [ETC]
        }
于 2013-09-03T14:32:10.880 回答