Wednesday, February 2, 2011

How to preserve the map center as the browser resizes

By default, when a Silverlight map (or its parent) is resized the map scale (or resolution) is preserved but not the map center. Instead, the map is “pinned” to the upper left hand corner.

In most situations this is desirable but occasionally it is not. The following code snippet will ensure that the current map center (and scale) is preserved as the browser is resized.

using System;
using System.Windows;
using System.Windows.Controls;
using ESRI.ArcGIS.Client.Geometry;

namespace SilverlightApplication2 {
    public partial class MainPage : UserControl {
        public MainPage() {
            InitializeComponent();

            this.SizeChanged += (s, e) => {
                if (e.PreviousSize.Height == 0 ||
e.PreviousSize.Width == 0) { return; }
                Point p = new Point() {
                    X = (this.MyMap.ActualWidth / 2d) -
(e.NewSize.Width - e.PreviousSize.Width),
                    Y = (this.MyMap.ActualHeight / 2d) -
(e.NewSize.Height - e.PreviousSize.Height)
                };
                MapPoint m = this.MyMap.ScreenToMap(p);
                TimeSpan t = this.MyMap.PanDuration;
                this.MyMap.PanDuration = TimeSpan.Zero;
                this.MyMap.PanTo(m);
                this.MyMap.PanDuration = t;
            };
        }
    }
}

No comments:

Post a Comment