Android xamarin google MapFragment.Map is null

in Xamarin android, when creating a MapFragment, the code shows the map, but mapFragment.Map is always null and I cannot set the map type

code:

var mapFragment = MapFragment.NewInstance (mapOptions);
FragmentTransaction tx = FragmentManager.BeginTransaction();
tx.Add(Resource.Id.map_fragment_container, mapFragment);

map = mapFragment.Map;
if (map != null) {
    map.MapType = GoogleMap.MapTypeNormal;//never comes to this line
}
tx.Commit();

      

XML:

<FrameLayout
    android:id="@+id/map_fragment_container"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

      

+3


source to share


3 answers


the reason was that the map view was not created at the point of the call

    var mapFragment = MapFragment.NewInstance (mapOptions); 

      



so I used a 500 millisecond delay before accessing the mapFragment.Map;

    handler.PostDelayed (UpdateMap, 500);


    void UpdateMap()
    {
        map = mapFragment.Map;
        if (map != null) {
            map.MapType = GoogleMap.MapTypeNormal;
            map.MoveCamera(cameraUpdate);
            return;
        }

        handler.PostDelayed(UpdateMap, 500);
    }

      

+1


source


I would put the code for creating the fragment in OnCreate and set the map to OnResume, something like this (excerpt from OnResume, use any option to find the fragment you prefer, or keep an instance of it when you create it):



            if (map == null)
            {
                if (mapFragment == null)
                {
                    mapFragment = ChildFragmentManager.FindFragmentByTag("map") as MapFragment;
                }


                map = mapFragment.Map;

                if (map != null)
                {
                   ....

      

+1


source


If you call MapFragment.NewInstance (mapOptions)

in action OnCreate

, you can extend MapFragment

and override OnActivityCreated

where the map should already be initialized.
You should still check it for null

, as the service itself may not be available.

This issue is discussed and explained well here .

0


source







All Articles