3

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" />
poupou
  • 43,413
  • 6
  • 77
  • 174
Salome Tsiramua
  • 763
  • 3
  • 9
  • 21

3 Answers3

1

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);
    }
Salome Tsiramua
  • 763
  • 3
  • 9
  • 21
  • 1
    This is a **very** bad idea, don't use delays in the form of time period as it is unreliable. Check the documentation if it's an async action (which I doubt) you should wait for it to finish, otherwise you have some other issue and setting a "timeout" helped by accident. – Alex.F Nov 05 '14 at 16:54
  • @Alex.F Thank you for your reply, can you suggest me a better solution for my problem? – Salome Tsiramua Nov 06 '14 at 12:38
  • I had the same problem. I fixed by by re-calling the map creation in onResume. Sometimes the map is not null, but if you do a check in onCreate, then retry in onResume it works. Let me know if you want a code sample, but it is handled this way in the current Xamarin Droid samples – Craig Champion Mar 13 '15 at 09:58
1

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)
                {
                   ....
Miha Markic
  • 3,158
  • 22
  • 28
0

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.

Community
  • 1
  • 1
Alex.F
  • 5,648
  • 3
  • 39
  • 63