Google Maps api v2, MapFragment Map property is always null even after initalizing

Hi,

I'm currently messing around with the Google Maps api and am trying to display a marker but no matter what the Map property of my fragment is null. I have no idea why, here is my code:

using System;

using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
using Android.Gms.Maps;
using Android.Gms.Maps.Model;

namespace ezriderandroid
{
[Activity (Label = "ez-rider-android", MainLauncher = true)]
public class MainActivity : Activity
{
int count = 1;

    MapFragment _myMapFragment;

    protected override void OnCreate (Bundle bundle)
    {
        base.OnCreate (bundle);

        // Set our view from the "main" layout resource
        SetContentView (Resource.Layout.Main);
        _myMapFragment = FragmentManager.FindFragmentByTag("map") as MapFragment;
        if (_myMapFragment == null)
        {
            GoogleMapOptions mapOptions = new GoogleMapOptions()
                .InvokeMapType(GoogleMap.MapTypeSatellite)
                .InvokeZoomControlsEnabled(false)
                .InvokeCompassEnabled(true);

            FragmentTransaction fragTx = FragmentManager.BeginTransaction();
            _myMapFragment = MapFragment.NewInstance(mapOptions);
            fragTx.Add(Resource.Id.map, _myMapFragment, "map");
            fragTx.Commit();
        }

        GoogleMap map = _myMapFragment.Map;

        if (map != null) {
            MarkerOptions markerOpt1 = new MarkerOptions();
            markerOpt1.SetPosition(new LatLng(50.379444, 2.773611));
            markerOpt1.SetTitle("Vimy Ridge");
            Marker marker1 = map.AddMarker(markerOpt1);
        }

// _myMapFragment = MapFragment.NewInstance();
// FragmentTransaction tx = FragmentManager.BeginTransaction();
// tx.Add(Resource.Id.my_mapfragment_container, _myMapFragment);
// tx.Commit();

        // Get our button from the layout resource,
        // and attach an event to it

// Button button = FindViewById (Resource.Id.myButton);
//
// button.Click += delegate {
// button.Text = string.Format ("{0} clicks!", count++);
// };
}
}
}

Posts

  • TomOpgenorthTomOpgenorth CAXamarin Team Xamurai

    It can take a while for the Google Play Services to initialize everything necessary for the MapFragment and until all that happens the .Map property will be null. This means that it's possible the .Map instance might be null in OnCreate.

    Basically, you need to check if _myMapFragment.Map is null before you try to use it. You can see an example of this the Maps And Location Demo v3 code.

Sign In or Register to comment.