Android.Gms.Maps.MapFragment.Map is obsolete deprecated xamarin android

It is always not recommended to use Obsolete API, as it involves risk of non-functioning at any point of time. In this post let us see the alternate for Google map obsolete api MapFragment.Map.

In  previous post i explained Integration of google map v2 in xamarin android,How to use Google geocode and reverse geocode api in xamarin.android, How to use Google Place API with Autocomplete in Xamarin Android,Integrating Google Account in Xamarin.Android, How to customize AlertDialog in xamarin.Android.

Using the "Map" Property of the "MapFragment" marks with a warning "Android.Gms.Maps.MapFragment.Map is obsolete deprecated". 
Instead need to make use of the method GetMapAsync(),which expects implementation of callback object of type IOnMapReadyCallback.

//OnMapReadyClass
public class OnMapReadyClass :Java.Lang.Object,IOnMapReadyCallback
    { 
  public GoogleMap Map { get; private set; }
  public event Action<GoogleMap> MapReadyAction;

  public void OnMapReady (GoogleMap googleMap)
     {
        Map = googleMap; 
  
        if ( MapReadyAction != null )
           MapReadyAction (Map);
     }
    }
Interface IOnMapReadyCallback has a method named "OnMapReady()" which returns a instance of Google Map.This class is inherited from Java.Lang.Object because,
To execute the virtual or interface method which is an overriden or implemented in managed code, xamarin.android need to provide Java proxy which converts methods to a proper Managed type. Since monodroid.exe looks for a Java.Lang.Object subclass and Java.Lang.Object implements IJavaObject. 
All Android classes and interface extend the Android.Runtime.IJavaObject interface.[Java integration,Android callable wrapper]


Here event Action is used to return the initialized google map instance back to the activity method.
Now Call the GetMapAsync() and event Action return map instance on successful Map initialization.
 
//MyActivityClass.cs 
 GoogleMap map;
 bool SetUpGoogleMap()
    {
      if(null != map ) return false;

      var frag = FragmentManager.FindFragmentById<mapfragment>(Resource.Id.map);
      var mapReadyCallback = new OnMapReadyClass();
  
      mapReadyCallback.MapReadyAction += delegate(GoogleMap googleMap )
        {
         map=googleMap; 
        };

      frag.GetMapAsync(mapReadyCallback); 
      return true;
    }


No comments:

Post a Comment