This is on Xamarin.Android.
Due to a known memory leak, we have created a static MapView and static Graphic Overlays for reuse. We received this error when loading a "GraphicOverlay" into the MapViews "GraphicsOverlays".
The code that runs to load the layers
Snippet
App.MapView.GraphicsOverlays.Clear(); App.MapView.GraphicsOverlays.Add(_plannedRouteGraphics); App.MapView.GraphicsOverlays.Add(_routeGraphicsLayer); App.MapView.GraphicsOverlays.Add(_deviceRouteGraphicsLayer); App.View.GraphicsOverlays.Add(_directionGraphics); App.MapView.GraphicsOverlays.Add(_directionArrowGraphics); App.MapView.GraphicsOverlays.Add(_stopGraphics);
Not all the time, but we from time to time get the following Exception
A layer can only belong to one map, and a map as well as graphics overlays can only belong to one mapview at a time.
So if you are reusing your overlays, make sure they get disconnected from the old mapview before assigning them to a new mapview. One way to do this is when you leave a page, to unhook them from the mapview control. Ie mapView.GraphicsOverlays = null; (or clear out the binding / datacontext if you're binding). That ensures things gets unhooked immediately rather than waiting for the garbage collector to break the link.
So calling MapView.GraphicsOverlays.Clear() isn't enough? I have to make it null, then create a new collection for the disassociation to work?
Another piece of information, is that both the Map and MapView are static as well as the graphic overlays so they are really if anything just rehooking to itself (to ensure properly z order).
We have
static MapView mapView;
static Map map;
static Dictionary<string, GraphicOverlay> overlays;
Code when setting up the page on the fragment
//Load map
if(mapView?.Map?.LoadStatus != LoadStatus.Loaded)
{
map = MapManager.GetMap(/* parameters to load type */);
mapView.Map = map;
}
//Load layers
mapView.GraphicOverlays.Clear();
_plannedRouteGraphics = overlays["NameOfFragment_PlannedRoute"];
_plannedRouteGraphics.Clear();
//Same code for a few other graphics
mapView.GraphicOverlays.Add(_plannedRouteGraphics);
Is it solved your issue? Still, am facing the same issue i.e., Object already owned
If you see that exception message it is because you are attempting to share something that has a specific ownership hierarchy (e.g. renderers and graphics overlay)
Please can you share your code to help us advise you on a resolution?
Cheers
Mike
I am using the same map package to display in two different fragments. How
to resolve it?
Regards,
Shylendra.
Make sure the Map is unhooked from the MapView in the previous fragment before assigning it to a new view.
Okay got it thanks for the response.
Regards,
Shylendra.
I was getting this "already owned" exception with 100.7 on WPF.
I'm using MVVM with an observablecollection of MapVMs where each MapVM has a Map property.
This behavior seems to fix the issue.
At first I tried doing this in OnDetaching, but it never gets called (shouldn't it?)