Salome Tsiramua
Salome Tsiramua

Reputation: 763

android xamarin google MapFragment.Map is null

in Xamarin android, creating MapFragment, the code shows map, but mapFragment.Map is always null and I can't set 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" />

Upvotes: 3

Views: 1393

Answers (3)

Alex.F
Alex.F

Reputation: 6181

If you call MapFragment.NewInstance (mapOptions) in the activity's OnCreate then you can extend MapFragment and override OnActivityCreated where the map should be already initialized.
You should still check it for null as the service itself might not be available.

This issue is discussed and explained well here.

Upvotes: 0

Miha Markic
Miha Markic

Reputation: 3240

I'd put fragment creation code in OnCreate and map setup in OnResume, something like that (excerpt from OnResume, use whatever option to find the fragment you prefer or store its instance when you create it):

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


                map = mapFragment.Map;

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

Upvotes: 1

Salome Tsiramua
Salome Tsiramua

Reputation: 763

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

    var mapFragment = MapFragment.NewInstance (mapOptions); 

so I used 500 milliseconds delay before accessing 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);
    }

Upvotes: 1

Related Questions