ClemensFischer / XAML-Map-Control

XAML Map Control Library
Microsoft Public License
203 stars 59 forks source link

Zoom out and centre map to view a number of locations/pins #88

Closed JYouren closed 2 years ago

JYouren commented 2 years ago

I have a list of Location objects which are shown on the map surface as Pushpins.

I would like to implement a 'Show All' feature, which would calculate a bounding box that includes all the points, adds an extra bit to ensure the locations are not directly on the edge of the window, and then zoom and centre to show them onscreen.

Would you be able to direct me in the right direction?

andyesys commented 2 years ago

This is what I have done in my project:

public void ZoomToBounds(BoundingBox boundingBox)
{
    var rect = MainMap.MapProjection.BoundingBoxToRect(boundingBox);
    var center = new Point(rect.X + (rect.Width / 2d), rect.Y + (rect.Height / 2d));
    var scale = Math.Min(MainMap.ActualWidth / rect.Width, MainMap.ActualHeight / rect.Height);
    var zoomLevel = ViewTransform.ScaleToZoomLevel(scale);
    // Set new view
    MainMap.TargetZoomLevel = Math.Floor(Math.Min(16, zoomLevel));
    MainMap.TargetCenter = MainMap.MapProjection.MapToLocation(center);
    MainMap.TargetHeading = 0d;
}

The parameter boundingBox is the rectangular bounds of all your pins lat/lon coordinates buffered by maybe 20%.

MainMap is the reference to the main MapControl.

JYouren commented 2 years ago

Thank you @andyesys, much appreciated