Wednesday 1 December 2010

Why does my Map Zoom property keep being reset to 1?


While working on my phone application I encountered an odd problem, after loading and setting my Map's ZoomLevel it promptly got set to 1 instead.
My setup was simple, in line with the MVVM pattern I had a MapControl's Zoom and Center properties databound to my View Model object. At the start of my application I loaded the View Models Zoom and Center values from a file on disk and this worked fine. But when my application resumed and I loaded these from the application state object instead they would be loaded and set correctly but immediately afterwards the Zoom would be overridden by the value 1.
Turns out the problem is caused by the order in which I set the two properties.
Apparently if you set the Center first and the Zoomlevel second the databinding circle sets the Zoom to a previous version (in my case 1). Do it the other way around and it works perfectly. Feels counterintuitive but it probably has to do with the fact that internally Zoom level and Center are converted into a Bounding box and that box is then databound back at the Zoom value of the control. So:
Wrong:
this.Center = (GeoCoordinate)PhoneApplicationService.Current.State["Center"];
this.ZoomLevel = (double)PhoneApplicationService.Current.State["ZoomLevel"];

Right:
this.ZoomLevel = (double)PhoneApplicationService.Current.State["ZoomLevel"];
this.Center = (GeoCoordinate)PhoneApplicationService.Current.State["Center"];

No comments:

Post a Comment